forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalytics_manager.dart
More file actions
2209 lines (1832 loc) · 79.9 KB
/
Copy pathanalytics_manager.dart
File metadata and controls
2209 lines (1832 loc) · 79.9 KB
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
import 'dart:async';
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:flutter/foundation.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:omi/backend/preferences.dart';
import 'package:omi/backend/schema/bt_device/bt_device.dart';
import 'package:omi/backend/schema/conversation.dart';
import 'package:omi/backend/schema/memory.dart';
import 'package:omi/env/env.dart';
import 'package:omi/utils/analytics/adapters/posthog_adapter.dart';
import 'package:omi/utils/analytics/analytics_adapter.dart';
import 'package:omi/utils/analytics/intercom.dart';
import 'package:omi/utils/device.dart';
import 'package:omi/utils/platform/platform_service.dart';
import 'package:shared_preferences/shared_preferences.dart';
class AnalyticsManager {
static final AnalyticsManager _instance = AnalyticsManager._internal();
static AnalyticsAdapter? _adapter;
static bool _initStarted = false;
static final SharedPreferencesUtil _preferences = SharedPreferencesUtil();
static final Map<String, DateTime> _pendingTimedEvents = {};
static const Duration _pendingTimedEventTtl = Duration(hours: 1);
static const Duration _initTimeout = Duration(seconds: 2);
static const int _maxQueuedEvents = 200;
static const int _flushBatchSize = 20;
static const int _maxDeliveryAttempts = 3;
static const List<Duration> _retryDelays = [Duration(seconds: 1), Duration(seconds: 5), Duration(seconds: 30)];
static final List<_QueuedAnalyticsEvent> _queuedEvents = [];
static bool _flushScheduled = false;
static bool _flushInProgress = false;
static Timer? _retryTimer;
static int _droppedEvents = 0;
static Map<String, Object> _globalEventProperties = {'app_platform': _mobilePlatformName};
static bool _analyticsReady = false;
/// Inject the analytics adapter at boot. Must be called before [init].
/// Calling without ever configuring leaves every method as a no-op, which
/// is the right behavior for environments without an analytics key (e.g.
/// local dev with no PostHog token).
static void configure(AnalyticsAdapter adapter) {
assert(!_initStarted, 'AnalyticsManager.configure() must be called before init().');
_adapter = adapter;
}
static Future<void> init({Duration timeout = _initTimeout}) async {
_initStarted = true;
if (_adapter == null && Env.posthogApiKey != null) {
_adapter = PostHogAnalyticsAdapter(apiKey: Env.posthogApiKey!);
}
final adapter = _adapter;
if (adapter == null) return;
try {
await PlatformService.executeIfSupportedAsync(
PlatformService.isAnalyticsSupported,
adapter.init,
).timeout(timeout);
await _loadGlobalEventProperties(timeout: timeout);
await _loadPersonPropertyCache();
_analyticsReady = true;
_retryTimer?.cancel();
_retryTimer = null;
_scheduleFlush();
} catch (_) {}
}
static Future<void> flushPending({bool force = false}) => _flushQueuedEvents(force: force);
@visibleForTesting
static int get queuedEventCountForTesting => _queuedEvents.length;
@visibleForTesting
static int get droppedEventCountForTesting => _droppedEvents;
@visibleForTesting
static Duration retryDelayForTesting(int attempts) => _retryDelayForAttempt(attempts);
@visibleForTesting
static void resetForTesting() {
_adapter = null;
_initStarted = false;
_pendingTimedEvents.clear();
_lastSentPersonProperty.clear();
_personPropertyCacheLoaded = false;
_queuedEvents.clear();
_flushScheduled = false;
_flushInProgress = false;
_retryTimer?.cancel();
_retryTimer = null;
_droppedEvents = 0;
_globalEventProperties = {'app_platform': _mobilePlatformName};
_analyticsReady = false;
}
factory AnalyticsManager() {
return _instance;
}
AnalyticsManager._internal();
void setUserAttribute(String key, dynamic value) {
setUserProperty(key, value);
PlatformService.executeIfSupported(PlatformService.isIntercomSupported, () {
IntercomManager.instance.updateCustomAttributes({key: value});
});
}
void setUserAttributes() {
setPeopleValues();
PlatformService.executeIfSupported(PlatformService.isIntercomSupported, () {
IntercomManager.instance.setUserAttributes();
});
}
void trackEvent(String eventName, {Map<String, dynamic>? properties}) {
track(eventName, properties: properties);
}
void setInteractionContext({String? screenName, required String target}) =>
PlatformService.executeIfSupported(PlatformService.isAnalyticsSupported, () {
final adapter = _adapter;
if (adapter == null || !adapter.isInitialized) return;
try {
adapter.setInteractionContext(screenName: screenName, target: target);
} catch (_) {}
});
setPeopleValues() {
_setUserPropertiesBatch({
'Notifications Enabled': _preferences.notificationsEnabled,
'Location Enabled': _preferences.locationEnabled,
'Apps Enabled Count': _preferences.enabledAppsCount,
'Apps Integrations Enabled Count': _preferences.enabledAppsIntegrationsCount,
'Speaker Profile': _preferences.hasSpeakerProfile,
'Calendar Enabled': _preferences.calendarEnabled,
'Primary Language': _preferences.userPrimaryLanguage,
'Authorized Storing Recordings': _preferences.permissionStoreRecordingsEnabled,
});
}
void setSubscriptionTier(String tier) => setUserProperty('Subscription Tier', tier);
setUserProperty(String key, dynamic value) => _setUserPropertiesBatch({key: value});
void _setUserPropertiesBatch(Map<String, dynamic> properties) =>
PlatformService.executeIfSupported(PlatformService.isAnalyticsSupported, () {
final adapter = _adapter;
if (adapter == null) return;
// If the SDK silently drops the identify call we must not cache it as
// sent — that would suppress every retry once the SDK is ready.
if (!adapter.isInitialized) return;
final uid = _preferences.uid;
if (uid.isEmpty) return;
final coerced = <String, Object>{};
properties.forEach((k, v) {
final c = _coerceProperty(v);
if (c != null) coerced[k] = c;
});
if (coerced.isEmpty) return;
final fresh = <String, Object>{};
final pending = <String, String>{};
coerced.forEach((k, v) {
final cacheKey = '$uid:$k';
final serialized = _serializePersonPropertyValue(v);
if (_lastSentPersonProperty[cacheKey] == serialized) return;
fresh[k] = v;
pending[cacheKey] = serialized;
});
if (fresh.isEmpty) return;
try {
adapter.identify(userId: uid, userProperties: fresh);
pending.forEach((cacheKey, serialized) {
_lastSentPersonProperty[cacheKey] = serialized;
_persistPersonPropertyCacheEntry(cacheKey, serialized);
});
} catch (_) {}
});
static const String _personPropertyCachePrefix = '_ph_lastset_';
static final Map<String, String> _lastSentPersonProperty = {};
static bool _personPropertyCacheLoaded = false;
static Future<void> _loadPersonPropertyCache() async {
if (_personPropertyCacheLoaded) return;
try {
final prefs = await SharedPreferences.getInstance();
for (final key in prefs.getKeys()) {
if (!key.startsWith(_personPropertyCachePrefix)) continue;
final v = prefs.getString(key);
if (v == null) continue;
_lastSentPersonProperty[key.substring(_personPropertyCachePrefix.length)] = v;
}
} catch (_) {}
_personPropertyCacheLoaded = true;
}
static Future<void> _persistPersonPropertyCacheEntry(String cacheKey, String value) async {
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('$_personPropertyCachePrefix$cacheKey', value);
} catch (_) {}
}
// Tagged so the bool `true` doesn't collide with the string `"true"`.
static String _serializePersonPropertyValue(Object value) {
if (value is bool) return 'b:$value';
if (value is num) return 'n:$value';
if (value is String) return 's:$value';
return 'x:${value.runtimeType}:$value';
}
static Future<void> _clearPersonPropertyCache() async {
_lastSentPersonProperty.clear();
_personPropertyCacheLoaded = false;
try {
final prefs = await SharedPreferences.getInstance();
final keys = prefs.getKeys().where((k) => k.startsWith(_personPropertyCachePrefix)).toList();
for (final k in keys) {
await prefs.remove(k);
}
} catch (_) {}
}
void optInTracking() {
PlatformService.executeIfSupported(PlatformService.isAnalyticsSupported, () {
final adapter = _adapter;
if (adapter == null) return;
try {
adapter.enable();
} catch (_) {}
identify();
});
}
void optOutTracking() {
PlatformService.executeIfSupported(PlatformService.isAnalyticsSupported, () {
final adapter = _adapter;
if (adapter == null) return;
try {
adapter.disable();
adapter.reset();
} catch (_) {}
unawaited(_clearPersonPropertyCache());
});
}
void identify({String? authMethod, DateTime? userCreatedAt, String userRole = 'member'}) {
PlatformService.executeIfSupported(PlatformService.isAnalyticsSupported, () {
final adapter = _adapter;
if (adapter == null) return;
final uid = _preferences.uid;
if (uid.isEmpty) return;
try {
adapter.identify(userId: uid);
} catch (_) {
return;
}
_instance.setPeopleValues();
_setUserPropertiesBatch({
if (authMethod != null) 'auth_method': authMethod,
if (userCreatedAt != null) 'user_created_at': userCreatedAt.toUtc().toIso8601String(),
'user_role': userRole,
});
setNameAndEmail();
});
}
void accountCreated({required String authProvider, String acquisitionSource = 'mobile_oauth'}) {
track(
'Account Created',
properties: {'is_first_auth': true, 'auth_provider': authProvider, 'acquisition_source': acquisitionSource},
);
}
void migrateUser(String newUid) {
PlatformService.executeIfSupported(PlatformService.isAnalyticsSupported, () {
final adapter = _adapter;
if (adapter == null) return;
unawaited(_clearPersonPropertyCache());
try {
adapter.alias(newUserId: newUid);
adapter.identify(userId: newUid);
} catch (_) {
return;
}
setNameAndEmail();
});
}
void setNameAndEmail() {
_setUserPropertiesBatch({'\$name': SharedPreferencesUtil().fullName, '\$email': SharedPreferencesUtil().email});
}
void track(String eventName, {Map<String, dynamic>? properties}) =>
PlatformService.executeIfSupported(PlatformService.isAnalyticsSupported, () {
final adapter = _adapter;
if (adapter == null) return;
final props = <String, Object>{};
if (properties != null) {
properties.forEach((k, v) {
final coerced = _coerceProperty(v);
if (coerced != null) props[k] = coerced;
});
}
_evictStaleTimedEvents();
final start = _pendingTimedEvents.remove(eventName);
if (start != null) {
props['\$duration'] = DateTime.now().difference(start).inMilliseconds / 1000.0;
}
_enqueueEvent(_QueuedAnalyticsEvent(eventName: eventName, properties: props));
});
static void _enqueueEvent(_QueuedAnalyticsEvent event) {
while (_queuedEvents.length >= _maxQueuedEvents) {
_queuedEvents.removeAt(0);
_droppedEvents++;
}
_queuedEvents.add(event);
_scheduleFlush();
}
static void _scheduleFlush() {
if (_flushScheduled || _flushInProgress || (_retryTimer?.isActive ?? false)) return;
_flushScheduled = true;
unawaited(
Future<void>.microtask(() async {
_flushScheduled = false;
await _flushQueuedEvents();
}),
);
}
static Future<void> _flushQueuedEvents({bool force = false}) async {
if (_flushInProgress) return;
if (force) {
_retryTimer?.cancel();
_retryTimer = null;
} else if (_retryTimer?.isActive ?? false) {
return;
}
var retryLater = false;
var flushAgain = false;
var retryDelay = _retryDelays.last;
_flushInProgress = true;
try {
final adapter = _adapter;
if (adapter == null || !adapter.isInitialized || !_analyticsReady) {
retryLater = _queuedEvents.isNotEmpty;
retryDelay = _retryDelays.last;
return;
}
var delivered = 0;
while (_queuedEvents.isNotEmpty && delivered < _flushBatchSize) {
final event = _queuedEvents.removeAt(0);
try {
adapter.track(eventName: event.eventName, properties: {...event.properties, ..._globalEventProperties});
delivered++;
} catch (_) {
final retriedEvent = event.nextAttempt();
_requeueOrDrop(retriedEvent);
retryLater = _queuedEvents.isNotEmpty;
retryDelay = _retryDelayForAttempt(event.attempts);
return;
}
}
flushAgain = _queuedEvents.isNotEmpty;
} finally {
_flushInProgress = false;
if (retryLater) {
_scheduleRetry(retryDelay);
} else if (flushAgain) {
_scheduleFlush();
}
}
}
static void _requeueOrDrop(_QueuedAnalyticsEvent event) {
if (event.attempts >= _maxDeliveryAttempts) {
_droppedEvents++;
return;
}
_queuedEvents.insert(0, event);
}
static Duration _retryDelayForAttempt(int attempts) {
final delayIndex = attempts <= 0 ? 0 : attempts;
if (delayIndex >= _retryDelays.length) return _retryDelays.last;
return _retryDelays[delayIndex];
}
static void _scheduleRetry(Duration delay) {
if (_retryTimer?.isActive ?? false) return;
_retryTimer = Timer(delay, _scheduleFlush);
}
void startTimingEvent(String eventName) =>
PlatformService.executeIfSupported(PlatformService.isAnalyticsSupported, () {
if (_adapter == null) return;
_evictStaleTimedEvents();
_pendingTimedEvents[eventName] = DateTime.now();
});
// Drop pending starts that exceeded the TTL — guards against unbounded growth
// when a startTimingEvent has no matching track() (navigation away, crash, short-circuit).
static void _evictStaleTimedEvents() {
if (_pendingTimedEvents.isEmpty) return;
final cutoff = DateTime.now().subtract(_pendingTimedEventTtl);
_pendingTimedEvents.removeWhere((_, started) => started.isBefore(cutoff));
}
void onboardingCompleted() => track('Onboarding Completed');
void onboardingStepCompleted(String step) => track('Onboarding Step $step Completed');
void onboardingUserAcquisitionSource(String source) =>
track('User Acquisition Source', properties: {'source': source});
// Interactive device onboarding
void deviceOnboardingStarted({String source = 'auto'}) =>
track('Device Onboarding Started', properties: {'source': source});
void deviceOnboardingStepCompleted(String step) =>
track('Device Onboarding Step Completed', properties: {'step': step});
void deviceOnboardingCompleted() => track('Device Onboarding Completed');
void deviceOnboardingAbandoned(int step) => track('Device Onboarding Abandoned', properties: {'step': step});
void deviceOnboardingDoubleTapConfigured(int action) =>
track('Device Onboarding Double Tap Configured', properties: {'action': action});
void settingsSaved({bool hasWebhookConversationCreated = false, bool hasWebhookTranscriptReceived = false}) => track(
'Developer Settings Saved',
properties: {
'has_webhook_memory_created': hasWebhookConversationCreated,
'has_webhook_transcript_received': hasWebhookTranscriptReceived,
},
);
void pageOpened(String name) {
setInteractionContext(screenName: name, target: 'screen');
track('$name Opened');
}
void appEnabled(String appId) {
track('App Enabled', properties: {'app_id': appId});
setUserProperty('Apps Enabled Count', _preferences.enabledAppsCount);
}
void appPurchaseStarted(String appId) => track('App Purchase Started', properties: {'app_id': appId});
void appPurchaseCompleted(String appId) => track('App Purchase Completed', properties: {'app_id': appId});
void privateAppSubmitted(Map<String, dynamic> properties) => track('Private App Submitted', properties: properties);
void publicAppSubmitted(Map<String, dynamic> properties) => track('Public App Submitted', properties: properties);
void appDisabled(String appId) {
track('App Disabled', properties: {'app_id': appId});
setUserProperty('Apps Enabled Count', _preferences.enabledAppsCount);
}
void appRated(String appId, double rating) {
track('App Rated', properties: {'app_id': appId, 'rating': rating});
}
void phoneMicRecordingStarted() => track('Phone Mic Recording Started');
void phoneMicRecordingStopped() => track('Phone Mic Recording Stopped');
void recordingUploadStarted({
required String attemptId,
required int fileCount,
required int totalBytes,
required bool claimsLiveCapture,
String? recordingId,
}) =>
track(
'Recording Upload Started',
properties: {
'upload_attempt_id': attemptId,
if (recordingId != null) 'recording_id': recordingId,
'file_count': fileCount,
'total_bytes': totalBytes,
'claims_live_capture': claimsLiveCapture,
'upload_source': 'offline_audio_queue',
},
);
void recordingUploadCompleted({
required String attemptId,
required int fileCount,
required int totalBytes,
required bool claimsLiveCapture,
required double durationSeconds,
required String result,
String? recordingId,
}) =>
track(
'Recording Upload Completed',
properties: {
'upload_attempt_id': attemptId,
if (recordingId != null) 'recording_id': recordingId,
'file_count': fileCount,
'total_bytes': totalBytes,
'claims_live_capture': claimsLiveCapture,
'upload_source': 'offline_audio_queue',
'duration_seconds': durationSeconds,
'result': result,
},
);
void recordingUploadFailed({
required String attemptId,
required int fileCount,
required int totalBytes,
required bool claimsLiveCapture,
required double durationSeconds,
required String failureClass,
String? recordingId,
}) =>
track(
'Recording Upload Failed',
properties: {
'upload_attempt_id': attemptId,
if (recordingId != null) 'recording_id': recordingId,
'file_count': fileCount,
'total_bytes': totalBytes,
'claims_live_capture': claimsLiveCapture,
'upload_source': 'offline_audio_queue',
'duration_seconds': durationSeconds,
'failure_class': failureClass,
},
);
// Transcribe Later (batch / offline capture)
void transcribeLaterToggled({required bool enabled}) =>
track('Transcribe Later Toggled', properties: {'enabled': enabled});
void transcribeLaterRecordingCaptured({int? durationSeconds}) =>
track('Transcribe Later Recording Captured', properties: {'duration_seconds': durationSeconds});
void transcribeLaterRecordingProcessed() => track('Transcribe Later Recording Processed');
// Phone Calls (VoIP)
void phoneCallPageOpened() => track('Phone Call Page Opened');
void phoneCallVerificationStarted() => track('Phone Call Verification Started');
void phoneCallVerificationCompleted() => track('Phone Call Verification Completed');
void phoneCallStarted({String? contactName}) =>
track('Phone Call Started', properties: {'has_contact_name': contactName != null});
void phoneCallConnected() => track('Phone Call Connected');
void phoneCallEnded({required int durationSeconds}) =>
track('Phone Call Ended', properties: {'duration_seconds': durationSeconds});
/// End-of-call (or stall) snapshot of the live-transcript session.
/// Aggregate counts and closed status strings only — no raw audio samples,
/// contact/phone numbers, transcripts, or ids are tracked.
void phoneCallTranscriptSession({
required bool wsAccepted,
required int audioFramesSent,
required int audioBytesSent,
required int audioChannel1Frames,
required int audioChannel2Frames,
required int eventChannelErrors,
required int eventChannelCoerced,
required String transcriptionStatusFinal,
required int durationSeconds,
String? reason,
}) =>
track(
'Phone Call Transcript Session',
properties: {
'ws_accepted': wsAccepted,
'audio_frames_sent': audioFramesSent,
'audio_bytes_sent': audioBytesSent,
'audio_channel_1_frames': audioChannel1Frames,
'audio_channel_2_frames': audioChannel2Frames,
'event_channel_errors': eventChannelErrors,
'event_channel_coerced': eventChannelCoerced,
'transcription_status_final': transcriptionStatusFinal,
'duration_seconds': durationSeconds,
if (reason != null) 'reason': reason,
},
);
void phoneCallFailed({String? error}) => track('Phone Call Failed', properties: {'error': error ?? 'unknown'});
// Phone Calls Dialpad
void phoneCallDialpadOpened() => track('Phone Call Dialpad Opened');
void phoneCallDialpadDigitPressed(String digit) =>
track('Phone Call Dialpad Digit Pressed', properties: {'digit': digit});
// Phone Calls Upsell
void phoneCallUpsellShown({required String source}) =>
track('Phone Call Upsell Shown', properties: {'source': source});
void phoneCallUpsellUpgradeTapped() => track('Phone Call Upsell Upgrade Tapped');
void phoneCallUpsellDismissed() => track('Phone Call Upsell Dismissed');
void appResultExpanded(ServerConversation conversation, String appId) {
track('App Result Expanded', properties: getConversationEventProperties(conversation)..['app_id'] = appId);
}
void languageChanged(String language) {
track('App Language Changed', properties: {'language': language});
setUserProperty('App Primary Language', language);
}
void recordingLanguageChanged(String language) {
track('Recording Language Changed', properties: {'language': language});
setUserProperty('Recordings Language', language);
}
void calendarEnabled() {
track('Calendar Enabled');
setUserProperty('Calendar Enabled', true);
}
void calendarDisabled() {
track('Calendar Disabled');
setUserProperty('Calendar Enabled', false);
}
void calendarModePressed(String mode) => track('Calendar Mode $mode Pressed');
void calendarSelected() => track('Calendar Selected');
void bottomNavigationTabClicked(String tab) {
setInteractionContext(screenName: tab, target: 'bottom_navigation');
track('Bottom Navigation Tab Clicked', properties: {'tab': tab});
}
void deviceConnected(BtDevice device) {
final vendor = device.type.analyticsVendor;
final hardwareFamily = DeviceUtils.analyticsHardwareFamily(device);
track(
'Device Connected',
properties: {
...device.toJson(),
'type': device.type.name,
'device_vendor': vendor,
'hardware_family': hardwareFamily,
..._deviceIdentityProperties(device),
},
);
setUserProperty('device_vendor', vendor);
setUserProperty('hardware_family', hardwareFamily);
}
void devicePaired(String firstPairedAt) {
final device = _preferences.btDevice;
final hardwareFamily = DeviceUtils.analyticsHardwareFamily(device);
track(
'Device Paired',
properties: {
...device.toJson(),
'type': device.type.name,
'device_vendor': device.type.analyticsVendor,
'hardware_family': hardwareFamily,
..._deviceIdentityProperties(device),
},
);
_setUserPropertiesBatch({
'has_paired_device': true,
'first_paired_at': firstPairedAt,
'device_vendor': device.type.analyticsVendor,
'hardware_family': hardwareFamily,
});
}
void deviceDisconnected() => track('Device Disconnected');
void deviceSessionEnded({required BtDevice device, required Duration duration, String? reason, int? hciReasonCode}) {
final properties = <String, Object>{
'duration_seconds': duration.inMilliseconds / Duration.millisecondsPerSecond,
'reason': _knownDeviceValue(reason ?? ''),
'device_vendor': device.type.analyticsVendor,
'hardware_family': DeviceUtils.analyticsHardwareFamily(device),
'model': _knownDeviceValue(device.modelNumber),
'firmware_revision': _knownDeviceValue(device.firmwareRevision),
};
if (hciReasonCode != null && hciReasonCode >= 0) {
properties['hci_reason_code'] = hciReasonCode;
}
track('Device Session Ended', properties: properties);
}
static String _knownDeviceValue(String value) => value.isEmpty || value == 'Unknown' ? 'unknown' : value;
static Map<String, Object> _deviceIdentityProperties(BtDevice device) {
final serial = device.serialNumber?.trim();
String hash(String value) => sha256.convert(utf8.encode(value)).toString().substring(0, 16);
final transportIdKind = switch (device.type) {
DeviceType.appleWatch => 'watch_identifier',
DeviceType.limitless => 'limitless_identifier',
DeviceType.raybanMeta => 'rayban_identifier',
_ => 'ble_identifier',
};
return {
'transport_device_id': hash(device.id),
'transport_id_kind': transportIdKind,
'transport_id_stability': 'platform_dependent',
if (serial != null && serial.isNotEmpty && serial != 'Unknown') ...{
'hardware_id': hash(serial),
'hardware_id_kind': 'manufacturer_serial',
'hardware_id_stable': true,
} else ...{
'hardware_id_kind': 'unavailable',
'hardware_id_stable': false,
},
};
}
void memoriesPageCategoryOpened(MemoryCategory category) =>
track('Fact Page Category Opened', properties: {'category': category.toString().split('.').last});
void memoriesPageDeletedMemory(Memory memory) =>
track('Fact Page Deleted Fact', properties: {'fact_category': memory.category.toString().split('.').last});
void memoriesPageEditedMemory() => track('Fact Page Edited Fact');
void memoriesPageCreateMemoryBtn() => track('Fact Page Create Fact Button Pressed');
void memoriesPageCreatedMemory(MemoryCategory category) =>
track('Fact Page Created Fact', properties: {'fact_category': category.toString().split('.').last});
void memorySearched(String query, int resultsCount) {
track(
'Fact Searched',
properties: _searchProperties(query: query, resultsCount: resultsCount, surface: 'facts'),
);
}
void memorySearchCleared(int totalFactsCount) {
track('Fact Search Cleared', properties: {'total_facts_count': totalFactsCount});
}
void memoryListItemClicked(Memory memory) {
track(
'Fact List Item Clicked',
properties: {'fact_id': memory.id, 'fact_category': memory.category.toString().split('.').last},
);
}
void memoryVisibilityChanged(Memory memory, MemoryVisibility newVisibility) {
track(
'Fact Visibility Changed',
properties: {
'fact_id': memory.id,
'fact_category': memory.category.toString().split('.').last,
'new_visibility': newVisibility.name,
},
);
}
/// "Things I learned today" card became visible. Counts only — the card's
/// content and memory ids never leave the device through analytics.
void memoryReviewCardShown({required int itemCount, required String source}) {
track('memory_review_card_shown', properties: {'item_count': itemCount, 'source': source});
}
/// One accept / reject / edit verdict on a learned memory.
///
/// [action] is accept|reject|edit, [outcome] is ok|error, [source] is
/// chat_block|daily_summary_detail. `memory_category` is the coarse category
/// label; no memory content and no raw memory id are ever attached.
void memoryReviewAction({
required String source,
required String action,
required String outcome,
required String memoryCategory,
}) {
track(
'memory_review_action',
properties: {'source': source, 'action': action, 'outcome': outcome, 'memory_category': memoryCategory},
);
}
/// The one grounded follow-up chip under an answer was tapped.
///
/// Mobile has no `question_asked` event to attribute to, so the origin is
/// carried by this event instead of as a property on a send event.
void followUpChipTapped({required String source}) {
track('followup_chip_tapped', properties: {'source': source});
}
void memoriesAllVisibilityChanged(MemoryVisibility newVisibility, int count) {
track('All Facts Visibility Changed', properties: {'new_visibility': newVisibility.name, 'facts_count': count});
}
void memoriesAllDeleted(int countBeforeDeletion) {
track('All Facts Deleted', properties: {'facts_count_before_deletion': countBeforeDeletion});
}
void memoriesFiltered(String filter) => track('Facts Filtered', properties: {'filter': filter});
void memoriesManagementSheetOpened() => track('Facts Management Sheet Opened');
Map<String, dynamic> _getTranscriptProperties(String transcript) {
String transcriptCopy = transcript.substring(0, transcript.length);
int speakersCount = 0;
for (int i = 0; i < 5; i++) {
if (transcriptCopy.contains('Speaker $i:')) speakersCount++;
transcriptCopy = transcriptCopy.replaceAll('Speaker $i:', '');
}
transcriptCopy = transcriptCopy.replaceAll(' ', ' ').trim();
return {
'transcript_length': transcriptCopy.length,
'transcript_word_count': transcriptCopy.split(' ').length,
'speaker_count': speakersCount,
};
}
Map<String, dynamic> getConversationEventProperties(ServerConversation convo) {
var properties = _getTranscriptProperties(convo.getTranscript());
int hoursAgo = DateTime.now().difference(convo.createdAt).inHours;
properties['memory_hours_since_creation'] = hoursAgo;
properties['memory_id'] = convo.id;
properties['memory_discarded'] = convo.discarded;
return properties;
}
void conversationCreated(ServerConversation conversation, {BtDevice? recordingDevice}) {
var properties = getConversationEventProperties(conversation);
properties['memory_result'] = conversation.discarded ? 'discarded' : 'saved';
properties['action_items_count'] = conversation.structured.actionItems.length;
properties['transcript_language'] = _preferences.userPrimaryLanguage;
// Additional properties for conversation creation
properties['conversation_source'] = conversation.source?.toString().split('.').last ?? 'unknown';
properties['duration_seconds'] = conversation.getDurationInSeconds();
properties['timestamp'] = conversation.createdAt.toIso8601String();
properties.addAll(recordingDeviceProperties(recordingDevice));
// Get the summarized app info if available
if (conversation.appResults.isNotEmpty) {
var summarizedApp = conversation.appResults.firstOrNull;
if (summarizedApp != null && summarizedApp.appId != null) {
properties['summary_app_id'] = summarizedApp.appId!;
}
}
track('Memory Created', properties: properties);
}
@visibleForTesting
static Map<String, Object> recordingDeviceProperties(BtDevice? device) => {
'recording_hardware_type': device?.type.name ?? 'phone',
'recording_firmware_revision': device == null ? 'not_applicable' : _knownDeviceValue(device.firmwareRevision),
};
void conversationListItemClicked(ServerConversation conversation, int idx) =>
track('Memory List Item Clicked', properties: getConversationEventProperties(conversation));
void conversationShareButtonClick(ServerConversation conversation) =>
track('Memory Share Button Clicked', properties: getConversationEventProperties(conversation));
void conversationDeleted(ServerConversation conversation) =>
track('Memory Deleted', properties: getConversationEventProperties(conversation));
void chatMessageSent({
required String message,
required bool includesFiles,
required int numberOfFiles,
required String chatTargetId,
required bool isPersonaChat,
required bool isVoiceInput,
}) =>
track(
'Chat Message Sent',
properties: {
'message_length': message.length,
'message_word_count': message.split(' ').length,
'includes_files': includesFiles,
'number_of_files': numberOfFiles,
'chat_target_id': chatTargetId,
'is_persona_chat': isPersonaChat,
'is_voice_input': isVoiceInput,
},
);
void chatVoiceInputUsed({required String chatTargetId, required bool isPersonaChat}) {
track('Chat Voice Input Used', properties: {'chat_target_id': chatTargetId, 'is_persona_chat': isPersonaChat});
}
void speechProfileCapturePageClicked() => track('Speech Profile Capture Page Clicked');
void showDiscardedMemoriesToggled(bool showDiscarded) =>
track('Show Discarded Memories Toggled', properties: {'show_discarded': showDiscarded});
// Conversation Display Settings Events
void conversationDisplaySettingsOpened() => track('Conversation Display Settings Opened');
void showShortConversationsToggled(bool showShort) =>
track('Show Short Conversations Toggled', properties: {'show_short': showShort});
void showDiscardedConversationsToggled(bool showDiscarded) =>
track('Show Discarded Conversations Toggled', properties: {'show_discarded': showDiscarded});
void shortConversationThresholdChanged(int thresholdSeconds) => track(
'Short Conversation Threshold Changed',
properties: {'threshold_seconds': thresholdSeconds, 'threshold_minutes': thresholdSeconds ~/ 60},
);
void voiceResponseToggled(bool enabled) => track('Voice Response Audio Toggled', properties: {'enabled': enabled});
void voiceResponseModeChanged(int mode) {
const names = {0: 'off', 1: 'headphones_only', 2: 'always'};
track('Voice Response Mode Changed', properties: {'mode': names[mode] ?? 'unknown', 'mode_int': mode});
}
// Conversation Merge Events
void conversationMergeSelectionModeEntered() => track('Conversation Merge Selection Mode Entered');
void conversationMergeSelectionModeExited() => track('Conversation Merge Selection Mode Exited');
void conversationSelectedForMerge(String conversationId, int totalSelected) => track(
'Conversation Selected For Merge',
properties: {'conversation_id': conversationId, 'total_selected': totalSelected},
);
void conversationMergeInitiated(List<String> conversationIds) => track(
'Conversation Merge Initiated',
properties: {'conversation_count': conversationIds.length, 'conversation_ids': conversationIds},
);
void conversationMergeCompleted(String mergedConversationId, List<String> removedConversationIds) => track(
'Conversation Merge Completed',
properties: {
'merged_conversation_id': mergedConversationId,
'removed_count': removedConversationIds.length,
'removed_conversation_ids': removedConversationIds,
},
);
void conversationMergeFailed(List<String> conversationIds) => track(
'Conversation Merge Failed',
properties: {'conversation_count': conversationIds.length, 'conversation_ids': conversationIds},
);
// Important Conversation Share Events
void importantConversationNotificationReceived(String conversationId) =>
track('Important Conversation Notification Received', properties: {'conversation_id': conversationId});
void shareToContactsSheetOpened(String conversationId) =>
track('Share To Contacts Sheet Opened', properties: {'conversation_id': conversationId});
void shareToContactsSelected(String conversationId, int contactCount) => track(
'Share To Contacts Selected',
properties: {'conversation_id': conversationId, 'contact_count': contactCount},
);
void shareToContactsSmsOpened(String conversationId, int contactCount) => track(
'Share To Contacts SMS Opened',
properties: {'conversation_id': conversationId, 'contact_count': contactCount},
);
void chatMessageConversationClicked(ServerConversation conversation) =>
track('Chat Message Memory Clicked', properties: getConversationEventProperties(conversation));
void addManualConversationClicked() => track('Add Manual Memory Clicked');
void manualConversationCreated(ServerConversation conversation) =>
track('Manual Memory Created', properties: getConversationEventProperties(conversation));
void setUserProperties(String whatDoYouDo, String whereDoYouPlanToUseYourFriend, String ageRange) {
_setUserPropertiesBatch({
'What the user does': whatDoYouDo,
'Using Omi At': whereDoYouPlanToUseYourFriend,
'Age Range': ageRange,
});
}
void reProcessConversation(ServerConversation conversation) =>
track('Re-process Memory', properties: getConversationEventProperties(conversation));
void developerModeEnabled() {
track('Developer Mode Enabled');
setUserProperty('Dev Mode Enabled', true);
}
void developerModeDisabled() {
track('Developer Mode Disabled');
setUserProperty('Dev Mode Enabled', false);
}
void userIDCopied() => track('User ID Copied');
void exportMemories() => track('Dev Mode Export Memories');