forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreferences.dart
More file actions
793 lines (551 loc) · 30.6 KB
/
Copy pathpreferences.dart
File metadata and controls
793 lines (551 loc) · 30.6 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
import 'dart:convert';
import 'package:collection/collection.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:omi/backend/schema/app.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/backend/schema/message.dart';
import 'package:omi/backend/schema/person.dart';
import 'package:omi/models/custom_stt_config.dart';
import 'package:omi/models/stt_provider.dart';
import 'package:omi/utils/logger.dart';
class SharedPreferencesUtil {
static final SharedPreferencesUtil _instance = SharedPreferencesUtil._internal();
static SharedPreferences? _preferences;
factory SharedPreferencesUtil() {
return _instance;
}
SharedPreferencesUtil._internal();
String get deviceIdHash => _preferences?.getString('deviceIdHash') ?? '';
set deviceIdHash(String value) => _preferences?.setString('deviceIdHash', value);
static Future<void> init() async {
_preferences = await SharedPreferences.getInstance();
}
/// Picks up values written natively (the Dart cache doesn't see those otherwise).
static Future<void> reload() async {
await _preferences?.reload();
}
int get pendantPagesStored => getInt('pendantPagesStored');
bool get pendantDraining => getBool('pendantDraining');
bool get pendantStorageAlmostFull => getBool('pendantStorageAlmostFull');
set uid(String value) => saveString('uid', value);
String get uid => getString('uid');
//-------------------------------- Device ----------------------------------//
set btDevice(BtDevice value) {
saveString('btDevice', jsonEncode(value.toJson()));
}
Future<void> btDeviceSet(BtDevice value) async {
await saveString('btDevice', jsonEncode(value.toJson()));
}
BtDevice get btDevice {
final String device = getString('btDevice');
if (device.isEmpty) return BtDevice(id: '', name: '', type: DeviceType.omi, rssi: 0);
return BtDevice.fromJson(jsonDecode(device));
}
set deviceName(String value) => saveString('deviceName', value);
String get deviceName => getString('deviceName');
bool get deviceIsV2 => getBool('deviceIsV2');
set deviceIsV2(bool value) => saveBool('deviceIsV2', value);
bool get deviceOnboardingCompleted => getBool('deviceOnboardingCompleted');
set deviceOnboardingCompleted(bool value) => saveBool('deviceOnboardingCompleted', value);
bool get backgroundModeEnabled => getBool('backgroundModeEnabled');
set backgroundModeEnabled(bool value) => saveBool('backgroundModeEnabled', value);
// Batch (offline) capture mode: when on, BLE audio is stored to local .bin files
// by the native layer instead of being transcribed in real time. Mutually
// exclusive with the realtime transcription socket (see CaptureProvider).
bool get batchModeEnabled => getBool('batchModeEnabled');
set batchModeEnabled(bool value) => saveBool('batchModeEnabled', value);
// Phone-mic batch capture marker. false = explicit Transcribe Later (files
// named audio_omibatchphone_...), true = automatic offline fallback (files
// named audio_omibatchphoneauto_...). Read natively as flutter.phoneBatchAuto.
bool get phoneBatchAuto => getBool('phoneBatchAuto');
set phoneBatchAuto(bool value) => saveBool('phoneBatchAuto', value);
// Transcribe Later: pause capture (native writer drops packets, keeps the file
// open) so the user can mute a sensitive moment and resume the same recording.
bool get batchMuted => getBool('batchMuted');
set batchMuted(bool value) => saveBool('batchMuted', value);
// Realtime device mute (double-tap pause). Persisted so the mute survives an
// app kill/restart — otherwise the device silently resumes recording on the
// next reconnect even though the user muted it. Restored into
// CaptureProvider._isPaused at startup and re-applied on reconnect.
bool get deviceMuted => getBool('deviceMuted');
set deviceMuted(bool value) => saveBool('deviceMuted', value);
// Transcribe Later: one-shot flag — when set, the native writer finalizes the
// current file and starts a fresh one (manual "New recording" cut), then clears it.
bool get batchCutRequested => getBool('batchCutRequested');
set batchCutRequested(bool value) => saveBool('batchCutRequested', value);
// Set while interactive device onboarding has temporarily suspended Transcribe Later so the
// realtime demo works. Persisted so an app-kill mid-onboarding is self-healed on next capture start.
bool get batchModeSuspendedForOnboarding => getBool('batchModeSuspendedForOnboarding');
set batchModeSuspendedForOnboarding(bool value) => saveBool('batchModeSuspendedForOnboarding', value);
// Double tap behavior: 0 = end conversation (default), 1 = pause/mute, 2 = star ongoing conversation
int get doubleTapAction => getInt('doubleTapAction');
set doubleTapAction(int value) => saveInt('doubleTapAction', value);
// Keep backward compatibility
bool get doubleTapPausesMuting => doubleTapAction == 1;
set doubleTapPausesMuting(bool value) => doubleTapAction = value ? 1 : 0;
// Custom STT configuration
CustomSttConfig get customSttConfig {
final configJson = getString('customSttConfig');
if (configJson.isEmpty) return CustomSttConfig.defaultConfig;
try {
return CustomSttConfig.fromJson(jsonDecode(configJson));
} catch (e, stack) {
Logger.debug('Error parsing customSttConfig: $e');
Logger.debug('Stack: $stack');
return CustomSttConfig.defaultConfig;
}
}
Future<bool> saveCustomSttConfig(CustomSttConfig value) async {
return await saveString('customSttConfig', jsonEncode(value.toJson()));
}
bool get useCustomStt => customSttConfig.isEnabled;
// Whether offline recordings auto-sync to Omi when the device connects.
// Defaults to true (auto-sync on) — the feature is opt-out from introduction.
bool get autoSyncOfflineRecordings => getBool('autoSyncOfflineRecordings', defaultValue: true);
set autoSyncOfflineRecordings(bool value) => saveBool('autoSyncOfflineRecordings', value);
// Per-provider config storage
CustomSttConfig? getConfigForProvider(SttProvider provider) {
final json = getString('sttConfig_${provider.name}');
if (json.isEmpty) return null;
try {
return CustomSttConfig.fromJson(jsonDecode(json));
} catch (e) {
Logger.debug('Error loading config for ${provider.name}: $e');
return null;
}
}
Future<bool> saveConfigForProvider(SttProvider provider, CustomSttConfig config) {
return saveString('sttConfig_${provider.name}', jsonEncode(config.toJson()));
}
//----------------------------- Permissions ---------------------------------//
set notificationsEnabled(bool value) => saveBool('notificationsEnabled', value);
bool get notificationsEnabled => getBool('notificationsEnabled');
set locationEnabled(bool value) => saveBool('locationEnabled', value);
bool get locationEnabled => getBool('locationEnabled');
//---------------------- Developer Settings ---------------------------------//
String get webhookOnConversationCreated => getString('webhookOnConversationCreated');
set webhookOnConversationCreated(String value) => saveString('webhookOnConversationCreated', value);
String get webhookOnTranscriptReceived => getString('webhookOnTranscriptReceived');
set webhookOnTranscriptReceived(String value) => saveString('webhookOnTranscriptReceived', value);
String get webhookAudioBytes => getString('webhookAudioBytes');
set webhookAudioBytes(String value) => saveString('webhookAudioBytes', value);
String get webhookAudioBytesDelay => getString('webhookAudioBytesDelay');
set webhookDaySummary(String value) => saveString('webhookDaySummary', value);
String get webhookDaySummary => getString('webhookDaySummary');
set webhookAudioBytesDelay(String value) => saveString('webhookAudioBytesDelay', value);
set devModeJoanFollowUpEnabled(bool value) => saveBool('devModeJoanFollowUpEnabled', value);
bool get devModeJoanFollowUpEnabled => getBool('devModeJoanFollowUpEnabled');
set transcriptionDiagnosticEnabled(bool value) => saveBool('transcriptionDiagnosticEnabled', value);
bool get transcriptionDiagnosticEnabled => getBool('transcriptionDiagnosticEnabled');
set autoCreateSpeakersEnabled(bool value) => saveBool('autoCreateSpeakersEnabled', value);
bool get autoCreateSpeakersEnabled => getBool('autoCreateSpeakersEnabled', defaultValue: true);
// Goal tracker widget on homepage - default is true (experimental feature)
set showGoalTrackerEnabled(bool value) => saveBool('showGoalTrackerEnabled', value);
bool get showGoalTrackerEnabled => getBool('showGoalTrackerEnabled', defaultValue: true);
// Daily score widget on homepage - default is true
set showDailyScoreEnabled(bool value) => saveBool('showDailyScoreEnabled', value);
bool get showDailyScoreEnabled => getBool('showDailyScoreEnabled', defaultValue: true);
// Tasks widget on homepage - default is true
set showTasksEnabled(bool value) => saveBool('showTasksEnabled', value);
bool get showTasksEnabled => getBool('showTasksEnabled', defaultValue: true);
// Phone call floating button on home screen - default is true
set showPhoneCallButton(bool value) => saveBool('showPhoneCallButton', value);
bool get showPhoneCallButton => getBool('showPhoneCallButton', defaultValue: true);
// Voice response playback mode for hardware-button replies.
// 0 = off (never speak)
// 1 = headphones only — AirPods / wired / USB / AirPlay (default)
// 2 = always, including the phone speaker
// Default is 1 so Omi never blasts a private answer out of the speaker
// in public unless the user explicitly opts in.
set voiceResponseMode(int value) => saveInt('voiceResponseMode', value);
int get voiceResponseMode => getInt('voiceResponseMode', defaultValue: 1);
// VAD Gate — server-side voice activity gating to save Deepgram costs (experimental)
set vadGateEnabled(bool value) => saveBool('vadGateEnabled', value);
bool get vadGateEnabled => getBool('vadGateEnabled');
// Claude Agent — route chat through desktop agent VM (experimental)
set claudeAgentEnabled(bool value) => saveBool('claudeAgentEnabled', value);
bool get claudeAgentEnabled => getBool('claudeAgentEnabled');
// Notification frequency (0-5): 0 = off, 5 = most frequent. Default is 0 (disabled)
set notificationFrequency(int value) => saveInt('notificationFrequency', value);
int get notificationFrequency => getInt('notificationFrequency', defaultValue: 0);
// Task category order for drag-and-drop sorting persistence
// Format: { "today": ["id1", "id2"], "tomorrow": ["id3"] }
set taskCategoryOrder(Map<String, List<String>> value) {
final encoded = jsonEncode(value);
saveString('taskCategoryOrder', encoded);
}
Map<String, List<String>> get taskCategoryOrder {
final encoded = getString('taskCategoryOrder');
if (encoded.isEmpty) return {};
try {
final decoded = jsonDecode(encoded) as Map<String, dynamic>;
return decoded.map((key, value) => MapEntry(key, (value as List).cast<String>()));
} catch (e) {
return {};
}
}
// Task -> goal mapping (local UI state)
// Format: { "taskId": "goalId" }
set taskGoalLinks(Map<String, String> value) {
final encoded = jsonEncode(value);
saveString('taskGoalLinks', encoded);
}
Map<String, String> get taskGoalLinks {
final encoded = getString('taskGoalLinks');
if (encoded.isEmpty) return {};
try {
final decoded = jsonDecode(encoded) as Map<String, dynamic>;
return decoded.map((key, value) => MapEntry(key, value.toString()));
} catch (e) {
return {};
}
}
// Wrapped 2025 - track if user has viewed their wrapped
set hasViewedWrapped2025(bool value) => saveBool('hasViewedWrapped2025', value);
bool get hasViewedWrapped2025 => getBool('hasViewedWrapped2025', defaultValue: false);
set conversationEventsToggled(bool value) => saveBool('conversationEventsToggled', value);
bool get conversationEventsToggled => getBool('conversationEventsToggled');
set transcriptsToggled(bool value) => saveBool('transcriptsToggled', value);
bool get transcriptsToggled => getBool('transcriptsToggled');
set audioBytesToggled(bool value) => saveBool('audioBytesToggled', value);
bool get audioBytesToggled => getBool('audioBytesToggled');
set daySummaryToggled(bool value) => saveBool('daySummaryToggled', value);
bool get daySummaryToggled => getBool('daySummaryToggled');
bool get showSummarizeConfirmation => getBool('showSummarizeConfirmation', defaultValue: true);
set showSummarizeConfirmation(bool value) => saveBool('showSummarizeConfirmation', value);
bool get showSubmitAppConfirmation => getBool('showSubmitAppConfirmation', defaultValue: true);
set showSubmitAppConfirmation(bool value) => saveBool('showSubmitAppConfirmation', value);
bool get showInstallAppConfirmation => getBool('showInstallAppConfirmation', defaultValue: true);
set showInstallAppConfirmation(bool value) => saveBool('showInstallAppConfirmation', value);
bool get showFirmwareUpdateDialog => getBool('v2/showFirmwareUpdateDialog', defaultValue: true);
set showFirmwareUpdateDialog(bool value) => saveBool('v2/showFirmwareUpdateDialog', value);
String get otaWifiSsid => getString('otaWifiSsid', defaultValue: '');
set otaWifiSsid(String value) => saveString('otaWifiSsid', value);
String get otaWifiPassword => getString('otaWifiPassword', defaultValue: '');
set otaWifiPassword(String value) => saveString('otaWifiPassword', value);
int get conversationSilenceDuration => getInt('conversationSilenceDuration', defaultValue: 120);
set conversationSilenceDuration(int value) => saveInt('conversationSilenceDuration', value);
String get transcriptionModel => getString('transcriptionModel3', defaultValue: 'soniox');
set transcriptionModel(String value) => saveString('transcriptionModel3', value);
bool get onboardingCompleted => getBool('onboardingCompleted');
set onboardingCompleted(bool value) => saveBool('onboardingCompleted', value);
bool get permissionsCompleted => getBool('permissionsCompleted');
set permissionsCompleted(bool value) => saveBool('permissionsCompleted', value);
bool get aiConsentGiven => getBool('aiConsentGiven');
set aiConsentGiven(bool value) => saveBool('aiConsentGiven', value);
String gptCompletionCache(String key) => getString('gptCompletionCache:$key');
setGptCompletionCache(String key, String value) => saveString('gptCompletionCache:$key', value);
bool get optInAnalytics => getBool('optInAnalytics');
set optInAnalytics(bool value) => saveBool('optInAnalytics', value);
bool get optInEmotionalFeedback => getBool('optInEmotionalFeedback');
set optInEmotionalFeedback(bool value) => saveBool('optInEmotionalFeedback', value);
bool get devModeEnabled => getBool('devModeEnabled');
set devModeEnabled(bool value) => saveBool('devModeEnabled', value);
// Auto-recording feature (macOS only)
bool get autoRecordingEnabled => getBool('autoRecordingEnabled', defaultValue: true);
set autoRecordingEnabled(bool value) => saveBool('autoRecordingEnabled', value);
// Developer Diagnostics
bool get devLogsToFileEnabled => getBool('devLogsToFileEnabled');
set devLogsToFileEnabled(bool value) => saveBool('devLogsToFileEnabled', value);
bool get permissionStoreRecordingsEnabled => getBool('permissionStoreRecordingsEnabled');
set permissionStoreRecordingsEnabled(bool value) => saveBool('permissionStoreRecordingsEnabled', value);
bool get unlimitedLocalStorageEnabled => getBool('unlimitedLocalStorageEnabled');
set unlimitedLocalStorageEnabled(bool value) => saveBool('unlimitedLocalStorageEnabled', value);
// Whether connected device supports new multi-file storage sync (persisted so it works when disconnected)
bool get deviceSupportsMultiFileSync => getBool('deviceSupportsMultiFileSync');
set deviceSupportsMultiFileSync(bool value) => saveBool('deviceSupportsMultiFileSync', value);
bool get hasSpeakerProfile => getBool('hasSpeakerProfile');
set hasSpeakerProfile(bool value) => saveBool('hasSpeakerProfile', value);
bool get showDiscardedMemories => getBool('showDiscardedMemories', defaultValue: false);
set showDiscardedMemories(bool value) => saveBool('showDiscardedMemories', value);
// Show short conversations - default is false (hidden)
bool get showShortConversations => getBool('showShortConversations', defaultValue: false);
set showShortConversations(bool value) => saveBool('showShortConversations', value);
// Short conversation threshold in seconds - default is 60 (1 minute)
// Options: 60 (1 min), 120 (2 min), 180 (3 min), 240 (4 min), 300 (5 min)
int get shortConversationThreshold => getInt('v2/shortConversationThreshold', defaultValue: 0);
set shortConversationThreshold(int value) => saveInt('v2/shortConversationThreshold', value);
// Transcription settings (cached for fast preload)
bool get cachedSingleLanguageMode => getBool('cachedSingleLanguageMode');
set cachedSingleLanguageMode(bool value) => saveBool('cachedSingleLanguageMode', value);
List<String> get cachedTranscriptionVocabulary => getStringList('cachedTranscriptionVocabulary');
set cachedTranscriptionVocabulary(List<String> value) => saveStringList('cachedTranscriptionVocabulary', value);
// User primary language preferences
String get userPrimaryLanguage => getString('userPrimaryLanguage');
set userPrimaryLanguage(String value) => saveString('userPrimaryLanguage', value);
bool get hasSetPrimaryLanguage => getBool('hasSetPrimaryLanguage');
set hasSetPrimaryLanguage(bool value) => saveBool('hasSetPrimaryLanguage', value);
int get currentStorageBytes => getInt('currentStorageBytes');
set currentStorageBytes(int value) => saveInt('currentStorageBytes', value);
int get previousStorageBytes => getInt('previousStorageBytes');
set previousStorageBytes(int value) => saveInt('previousStorageBytes', value);
int get enabledAppsCount => appsList.where((element) => element.enabled).length;
int get enabledAppsIntegrationsCount =>
appsList.where((element) => element.enabled && element.worksExternally()).length;
bool get showConversationDeleteConfirmation {
if (!getBool('conversationDeleteCascadeMigrated')) {
saveBool('conversationDeleteCascadeMigrated', true);
saveBool('showConversationDeleteConfirmation', true);
return true;
}
return getBool('showConversationDeleteConfirmation', defaultValue: true);
}
set showConversationDeleteConfirmation(bool value) => saveBool("showConversationDeleteConfirmation", value);
bool get showActionItemDeleteConfirmation => getBool('showActionItemDeleteConfirmation', defaultValue: true);
set showActionItemDeleteConfirmation(bool value) => saveBool('showActionItemDeleteConfirmation', value);
bool get showGetOmiCard => getBool('showGetOmiCard', defaultValue: true);
set showGetOmiCard(bool value) => saveBool('showGetOmiCard', value);
List<App> get appsList {
final apps = getStringList('appsList');
return App.fromJsonList(apps.map((e) => jsonDecode(e)).toList());
}
set appsList(List<App> value) {
final List<String> apps = value.map((e) => jsonEncode(e.toJson())).toList();
saveStringList('appsList', apps);
}
enableApp(String value) {
final List<App> apps = appsList;
App? app = apps.firstWhereOrNull((element) => element.id == value);
if (app != null) {
app.enabled = true;
appsList = apps;
}
}
disableApp(String value) {
final List<App> apps = appsList;
App? app = apps.firstWhereOrNull((element) => element.id == value);
if (app != null) {
app.enabled = false;
appsList = apps;
}
}
String get selectedChatAppId => getString('selectedChatAppId2', defaultValue: 'no_selected');
set selectedChatAppId(String value) => saveString('selectedChatAppId2', value);
String get lastUsedSummarizationAppId => getString('lastUsedSummarizationAppId');
set lastUsedSummarizationAppId(String value) => saveString('lastUsedSummarizationAppId', value);
String get preferredSummarizationAppId => getString('preferredSummarizationAppId');
set preferredSummarizationAppId(String value) => saveString('preferredSummarizationAppId', value);
List<ServerConversation> get cachedConversations {
if (getBool('migratedMemories')) {
final cachedMemories = getStringList('cachedMemories');
if (cachedMemories.isNotEmpty) {
final conversations = cachedMemories.map((e) => ServerConversation.fromJson(jsonDecode(e))).toList();
cachedConversations = conversations;
saveBool('migratedMemories', true);
}
}
final conversations = getStringList('cachedConversations');
return conversations.map((e) => ServerConversation.fromJson(jsonDecode(e))).toList();
}
set cachedConversations(List<ServerConversation> value) {
final List<String> conversations = value.map((e) => jsonEncode(e.toJson())).toList();
saveStringList('cachedConversations', conversations);
}
List<ServerMessage> get cachedMessages {
final messages = getStringList('cachedMessages');
return messages.map((e) => ServerMessage.fromJson(jsonDecode(e))).toList();
}
set cachedMessages(List<ServerMessage> value) {
final List<String> messages = value.map((e) => jsonEncode(e.toJson())).toList();
saveStringList('cachedMessages', messages);
}
// Pending memories - memories created offline that need to be synced
List<Memory> get pendingMemories {
final ownerUid = uid;
if (ownerUid.isEmpty) return [];
_scopeLegacyUserData(ownerUid);
final memories = getStringList(_userScopedKey('pendingMemories', ownerUid));
return memories.map((e) => Memory.fromJson(jsonDecode(e))).where((memory) => memory.uid == ownerUid).toList();
}
set pendingMemories(List<Memory> value) {
final ownerUid = uid;
if (ownerUid.isEmpty) return;
final List<String> memories = value.map((e) => jsonEncode(e.toJson())).toList();
saveStringList(_userScopedKey('pendingMemories', ownerUid), memories);
}
void addPendingMemory(Memory memory) {
final List<Memory> memories = pendingMemories;
memories.add(memory);
pendingMemories = memories;
}
void removePendingMemory(String memoryId, {String? ownerUid}) {
final owner = ownerUid ?? uid;
if (owner.isEmpty) return;
final encoded = getStringList(_userScopedKey('pendingMemories', owner));
final memories = encoded.map((e) => Memory.fromJson(jsonDecode(e))).toList();
memories.removeWhere((m) => m.id == memoryId);
saveStringList(
_userScopedKey('pendingMemories', owner),
memories.map((memory) => jsonEncode(memory.toJson())).toList(),
);
}
void clearPendingMemories() {
final ownerUid = uid;
if (ownerUid.isEmpty) return;
saveStringList(_userScopedKey('pendingMemories', ownerUid), []);
}
List<Person> get cachedPeople {
final people = getStringList('cachedPeople');
return people.map((e) => Person.fromJson(jsonDecode(e))).toList();
}
Person? getPersonById(String id) {
return cachedPeople.firstWhereOrNull((element) => element.id == id);
}
set cachedPeople(List<Person> value) {
final List<String> people = value.map((e) => jsonEncode(e.toJson())).toList();
saveStringList('cachedPeople', people);
}
addCachedPerson(Person person) {
final List<Person> people = cachedPeople;
people.add(person);
cachedPeople = people;
}
removeCachedPerson(String personId) {
final List<Person> people = cachedPeople;
Person? person = people.firstWhereOrNull((p) => p.id == personId);
if (person != null) {
people.remove(person);
cachedPeople = people;
}
}
replaceCachedPerson(Person person) {
final List<Person> people = cachedPeople;
Person? oldPerson = people.firstWhereOrNull((p) => p.id == person.id);
if (oldPerson != null) {
people.remove(oldPerson);
people.add(person);
cachedPeople = people;
}
}
ServerConversation? get modifiedConversationDetails {
final String conversation = getString('modifiedConversationDetails');
if (conversation.isEmpty) return null;
return ServerConversation.fromJson(jsonDecode(conversation));
}
set modifiedConversationDetails(ServerConversation? value) {
saveString('modifiedConversationDetails', value == null ? '' : jsonEncode(value.toJson()));
}
set calendarPermissionAlreadyRequested(bool value) => saveBool('calendarPermissionAlreadyRequested', value);
bool get calendarPermissionAlreadyRequested => getBool('calendarPermissionAlreadyRequested');
set calendarEnabled(bool value) => saveBool('calendarEnabled', value);
bool get calendarEnabled => getBool('calendarEnabled');
//--------------------------------- Auth ------------------------------------//
String get authToken => getString('authToken');
set authToken(String value) => saveString('authToken', value);
int get tokenExpirationTime => getInt('tokenExpirationTime');
set tokenExpirationTime(int value) => saveInt('tokenExpirationTime', value);
String get email => getString('email');
set email(String value) => saveString('email', value);
String get givenName => getString('givenName');
set givenName(String value) => saveString('givenName', value);
String get familyName => getString('familyName');
set familyName(String value) => saveString('familyName', value);
String get fullName => '$givenName $familyName'.trim();
/// Clears persisted user identity and server-backed display caches while
/// preserving device, onboarding, permissions, and offline recording state.
void clearUserDisplayCache() {
final ownerUid = uid;
if (ownerUid.isNotEmpty) _scopeLegacyUserData(ownerUid);
authToken = '';
tokenExpirationTime = 0;
uid = '';
email = '';
givenName = '';
familyName = '';
cachedConversations = <ServerConversation>[];
cachedMessages = <ServerMessage>[];
cachedPeople = <Person>[];
appsList = <App>[];
modifiedConversationDetails = null;
cachedSingleLanguageMode = false;
cachedTranscriptionVocabulary = <String>[];
userPrimaryLanguage = '';
hasSetPrimaryLanguage = false;
hasSpeakerProfile = false;
selectedChatAppId = 'no_selected';
lastUsedSummarizationAppId = '';
preferredSummarizationAppId = '';
calendarEnabled = false;
_preferences?.remove('cachedMemories');
}
String _userScopedKey(String baseKey, String ownerUid) => '$baseKey:$ownerUid';
void scopeLegacyUserDataForCurrentUser() {
final ownerUid = uid;
if (ownerUid.isNotEmpty) _scopeLegacyUserData(ownerUid);
}
void _scopeLegacyUserData(String ownerUid) {
final preferences = _preferences;
if (preferences == null || ownerUid.isEmpty) return;
final pendingKey = _userScopedKey('pendingMemories', ownerUid);
final legacyPending = preferences.getStringList('pendingMemories');
if (legacyPending != null) {
final scopedPending = preferences.getStringList(pendingKey) ?? const <String>[];
preferences.setStringList(pendingKey, {...scopedPending, ...legacyPending}.toList());
}
preferences.remove('pendingMemories');
final goalsKey = _userScopedKey('goals_tracker_local_goals', ownerUid);
final legacyGoals = preferences.getString('goals_tracker_local_goals');
if (legacyGoals != null) {
final scopedGoals = preferences.getString(goalsKey);
preferences.setString(goalsKey, _mergeJsonLists(scopedGoals, legacyGoals));
}
preferences.remove('goals_tracker_local_goals');
}
String _mergeJsonLists(String? existing, String legacy) {
try {
final existingItems = existing == null ? <dynamic>[] : jsonDecode(existing) as List<dynamic>;
final legacyItems = jsonDecode(legacy) as List<dynamic>;
final merged = <String, dynamic>{};
for (final item in [...existingItems, ...legacyItems]) {
merged[jsonEncode(item)] = item;
}
return jsonEncode(merged.values.toList());
} catch (_) {
return existing ?? legacy;
}
}
String get foundOmiSource => getString('foundOmiSource');
set foundOmiSource(String value) => saveString('foundOmiSource', value);
set locationPermissionRequested(bool value) => saveBool('locationPermissionRequested', value);
bool get locationPermissionRequested => getBool('locationPermissionRequested');
set companionAssociationPrompted(bool value) => saveBool('companionAssociationPrompted', value);
bool get companionAssociationPrompted => getBool('companionAssociationPrompted');
//--------------------------- Announcements ---------------------------------//
// Last known app version - used to detect app upgrades
// Empty string means fresh install
String get lastKnownAppVersion => getString('lastKnownAppVersion');
set lastKnownAppVersion(String value) => saveString('lastKnownAppVersion', value);
// Last known firmware version - used to detect firmware upgrades
String get lastKnownFirmwareVersion => getString('lastKnownFirmwareVersion');
set lastKnownFirmwareVersion(String value) => saveString('lastKnownFirmwareVersion', value);
// Last time general announcements were checked
DateTime? get lastAnnouncementCheckTime {
final str = getString('lastAnnouncementCheckTime');
if (str.isEmpty) return null;
return DateTime.tryParse(str);
}
set lastAnnouncementCheckTime(DateTime? value) {
if (value == null) {
remove('lastAnnouncementCheckTime');
} else {
saveString('lastAnnouncementCheckTime', value.toUtc().toIso8601String());
}
}
//--------------------------- Setters & Getters -----------------------------//
String getString(String key, {String defaultValue = ''}) => _preferences?.getString(key) ?? defaultValue;
int getInt(String key, {int defaultValue = 0}) => _preferences?.getInt(key) ?? defaultValue;
bool getBool(String key, {bool defaultValue = false}) => _preferences?.getBool(key) ?? defaultValue;
double getDouble(String key, {double defaultValue = 0.0}) => _preferences?.getDouble(key) ?? defaultValue;
List<String> getStringList(String key, {List<String> defaultValue = const []}) =>
_preferences?.getStringList(key) ?? defaultValue;
Future<bool> saveString(String key, String value) async => await _preferences?.setString(key, value) ?? false;
Future<bool> saveInt(String key, int value) async => await _preferences?.setInt(key, value) ?? false;
Future<bool> saveBool(String key, bool value) async => await _preferences?.setBool(key, value) ?? false;
Future<bool> saveDouble(String key, double value) async => await _preferences?.setDouble(key, value) ?? false;
Future<bool> saveStringList(String key, List<String> value) async =>
await _preferences?.setStringList(key, value) ?? false;
Future<bool> remove(String key) async => await _preferences?.remove(key) ?? false;
Future<bool> clear() async => await _preferences?.clear() ?? false;
}