87 lines
2.5 KiB
Dart
87 lines
2.5 KiB
Dart
import 'package:shared_preferences/shared_preferences.dart';
|
|
import '../../../core/servers/server_scope.dart';
|
|
|
|
import 'notification_ledger.dart';
|
|
|
|
/// The persistence seam for the notification ledger.
|
|
///
|
|
/// The controller only ever hands over the exact string produced by
|
|
/// [encodeNotificationLedger], so a store cannot invent a different format.
|
|
/// Both directions are allowed to fail: a caller treats a null read as "nothing
|
|
/// recorded yet" and a false write as "this session only".
|
|
abstract interface class NotificationStore {
|
|
Future<String?> read();
|
|
|
|
Future<bool> write(String value);
|
|
}
|
|
|
|
/// `shared_preferences` storage under the ledger's own key.
|
|
///
|
|
/// Reads and writes are total: an unavailable plugin, a disabled store or a full
|
|
/// disk returns null/false instead of throwing into the caller's frame. Only the
|
|
/// documented [notificationStorageKey] is touched, never the attention key or the
|
|
/// legacy web key.
|
|
class SharedPreferencesNotificationStore implements NotificationStore {
|
|
const SharedPreferencesNotificationStore({this.serverId = ''});
|
|
final String serverId;
|
|
String get _key => scopedServerKey(notificationStorageKey, serverId);
|
|
|
|
Future<SharedPreferences?> _preferences() async {
|
|
try {
|
|
return await SharedPreferences.getInstance();
|
|
} catch (_) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
@override
|
|
Future<String?> read() async {
|
|
final preferences = await _preferences();
|
|
if (preferences == null) return null;
|
|
try {
|
|
return preferences.getString(_key);
|
|
} catch (_) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
@override
|
|
Future<bool> write(String value) async {
|
|
final preferences = await _preferences();
|
|
if (preferences == null) return false;
|
|
try {
|
|
return await preferences.setString(_key, value);
|
|
} catch (_) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// An in-memory store for tests and isolated fixtures.
|
|
///
|
|
/// It never touches the platform store, so a probe or widget test cannot mutate
|
|
/// a real operator's persisted ledger. [failReads] and [failWrites] reproduce an
|
|
/// unavailable store without throwing.
|
|
class MemoryNotificationStore implements NotificationStore {
|
|
MemoryNotificationStore({this.stored});
|
|
|
|
String? stored;
|
|
bool failReads = false;
|
|
bool failWrites = false;
|
|
int writes = 0;
|
|
|
|
@override
|
|
Future<String?> read() async {
|
|
if (failReads) throw StateError('notification store unavailable');
|
|
return stored;
|
|
}
|
|
|
|
@override
|
|
Future<bool> write(String value) async {
|
|
writes++;
|
|
if (failWrites) throw StateError('notification store is read-only');
|
|
stored = value;
|
|
return true;
|
|
}
|
|
}
|