Key per-channel storage by PSK-derived channel ID
Channel messages, settings, region, order and images were persisted by radio slot index, so a slot reused for a different channel inherited the old channel's history and settings (#359). - Channel.storageId: first 8 bytes of SHA-256("meshcore-channel:" + psk). - All per-channel stores key by channel ID; in-memory state stays by slot. - The connector keeps a slot -> channel ID map, diffs it against the saved map on every channel sync and reloads slots whose channel changed. - Queued channel frames wait until this session's map is confirmed. - One-shot per-radio migration from slot keys, using the cached channel list the legacy data was written under; rerun-safe if interrupted. - Deleting a channel clears its data; a channel removed elsewhere keeps its history and gets it back when re-added. A PSK edit keeps its place in the custom order. - Slots sharing a PSK share history and settings. - Image entries record their channel ID; a slot change resets that slot's in-progress reassembly.
This commit is contained in:
1 parent
d30744aa31
commit
679116ed03
24 files changed
+1794
-340
No files matched your search
@@ -1,13 +1,11 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
import 'package:meshcore_open/utils/app_logger.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../models/channel_message.dart';
|
||||
import '../models/message.dart' show legacyAwareReceivedAt;
|
||||
import '../models/translation_support.dart';
|
||||
import '../helpers/smaz.dart';
|
||||
import 'legacy_key_migration.dart';
|
||||
import 'prefs_manager.dart';
|
||||
|
||||
class ChannelMessageStore {
|
||||
@@ -30,11 +28,13 @@ class ChannelMessageStore {
|
||||
/// created by a screen to clear a key also resets the connector's view.
|
||||
static final Map<String, List<String>> _archived = {};
|
||||
|
||||
String _keyForChannel(String channelId) => '${keyFor}_$channelId';
|
||||
|
||||
/// Save messages for a specific channel: [messages] is the in-memory
|
||||
/// window (oldest first) and is written after the archived entries that
|
||||
/// sit ahead of it in storage.
|
||||
Future<void> saveChannelMessages(
|
||||
int channelIndex,
|
||||
String channelId,
|
||||
List<ChannelMessage> messages,
|
||||
) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
@@ -44,11 +44,11 @@ class ChannelMessageStore {
|
||||
return;
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$keyFor$channelIndex';
|
||||
final key = _keyForChannel(channelId);
|
||||
final visibleJson = messages.map(_messageToJson).toList();
|
||||
final archived =
|
||||
_archived[key] ??
|
||||
_unreconciledArchive(_readStored(prefs, channelIndex), visibleJson);
|
||||
_unreconciledArchive(prefs.getString(key), visibleJson);
|
||||
final overflow = archived.length + visibleJson.length - maxStoredMessages;
|
||||
if (overflow > 0) {
|
||||
archived.removeRange(0, overflow.clamp(0, archived.length));
|
||||
@@ -59,22 +59,22 @@ class ChannelMessageStore {
|
||||
}
|
||||
|
||||
/// Records [olderMessages] as the stored entries that precede the
|
||||
/// in-memory window for [channelIndex].
|
||||
void setArchived(int channelIndex, List<ChannelMessage> olderMessages) {
|
||||
_archived['$keyFor$channelIndex'] = olderMessages
|
||||
/// in-memory window for [channelId].
|
||||
void setArchived(String channelId, List<ChannelMessage> olderMessages) {
|
||||
_archived[_keyForChannel(channelId)] = olderMessages
|
||||
.map((message) => jsonEncode(_messageToJson(message)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Number of stored entries ahead of the in-memory window, or null when
|
||||
/// the window has not been reconciled with storage.
|
||||
int? archivedCount(int channelIndex) =>
|
||||
_archived['$keyFor$channelIndex']?.length;
|
||||
int? archivedCount(String channelId) =>
|
||||
_archived[_keyForChannel(channelId)]?.length;
|
||||
|
||||
/// Removes the newest [count] archived entries after they were paged back
|
||||
/// into the in-memory window.
|
||||
void unarchiveNewest(int channelIndex, int count) {
|
||||
final archived = _archived['$keyFor$channelIndex'];
|
||||
void unarchiveNewest(String channelId, int count) {
|
||||
final archived = _archived[_keyForChannel(channelId)];
|
||||
if (archived == null || count <= 0) return;
|
||||
archived.removeRange(
|
||||
(archived.length - count).clamp(0, archived.length),
|
||||
@@ -84,11 +84,11 @@ class ChannelMessageStore {
|
||||
|
||||
/// Drops the archive bookkeeping, for one channel or all of them, when the
|
||||
/// matching in-memory window is discarded.
|
||||
void forgetArchive([int? channelIndex]) {
|
||||
if (channelIndex == null) {
|
||||
void forgetArchive([String? channelId]) {
|
||||
if (channelId == null) {
|
||||
_archived.clear();
|
||||
} else {
|
||||
_archived.remove('$keyFor$channelIndex');
|
||||
_archived.remove(_keyForChannel(channelId));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,41 +118,17 @@ class ChannelMessageStore {
|
||||
return 'fallback:${json['timestamp']}:${json['senderName']}:${json['text']}';
|
||||
}
|
||||
|
||||
/// Reads the stored JSON for [channelIndex], migrating the legacy unscoped
|
||||
/// key on first access.
|
||||
String? _readStored(SharedPreferences prefs, int channelIndex) {
|
||||
final key = '$keyFor$channelIndex';
|
||||
final oldKey = '$_keyPrefix$channelIndex';
|
||||
final jsonString = prefs.getString(key);
|
||||
if ((jsonString == null || jsonString.isEmpty) &&
|
||||
canMigrateLegacyKeys(publicKeyHex)) {
|
||||
// Attempt migration from legacy unscoped key on first load
|
||||
final legacyJsonString = prefs.getString(oldKey);
|
||||
prefs.remove(oldKey);
|
||||
if (legacyJsonString != null && legacyJsonString.isNotEmpty) {
|
||||
appLogger.info(
|
||||
'Migrating channel messages from legacy key $oldKey to scoped key $key',
|
||||
);
|
||||
prefs.setString(key, legacyJsonString);
|
||||
return legacyJsonString;
|
||||
}
|
||||
}
|
||||
return jsonString;
|
||||
}
|
||||
|
||||
/// Load messages for a specific channel
|
||||
Future<List<ChannelMessage>> loadChannelMessages(int channelIndex) async {
|
||||
Future<List<ChannelMessage>> loadChannelMessages(String channelId) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn(
|
||||
'Public key hex is not set. Cannot load channel messages.',
|
||||
);
|
||||
return [];
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
String? jsonString = _readStored(prefs, channelIndex);
|
||||
if (jsonString == null || jsonString.isEmpty) {
|
||||
jsonString = prefs.getString(keyFor);
|
||||
}
|
||||
final jsonString = PrefsManager.instance.getString(
|
||||
_keyForChannel(channelId),
|
||||
);
|
||||
if (jsonString == null || jsonString.isEmpty) {
|
||||
return [];
|
||||
}
|
||||
@@ -161,7 +137,7 @@ class ChannelMessageStore {
|
||||
jsonList = jsonDecode(jsonString) as List<dynamic>;
|
||||
} catch (e) {
|
||||
appLogger.warn(
|
||||
'Stored messages for channel $channelIndex are unreadable: $e',
|
||||
'Stored messages for channel $channelId are unreadable: $e',
|
||||
);
|
||||
return [];
|
||||
}
|
||||
@@ -177,9 +153,9 @@ class ChannelMessageStore {
|
||||
}
|
||||
|
||||
/// Clear messages for a specific channel
|
||||
Future<void> clearChannelMessages(int channelIndex) async {
|
||||
Future<void> clearChannelMessages(String channelId) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$keyFor$channelIndex';
|
||||
final key = _keyForChannel(channelId);
|
||||
_archived[key] = [];
|
||||
await prefs.remove(key);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import 'dart:convert';
|
||||
import '../utils/app_logger.dart';
|
||||
import 'legacy_key_migration.dart';
|
||||
import 'prefs_manager.dart';
|
||||
|
||||
/// Persists the user's channel order as a list of channel storage IDs
|
||||
/// ([Channel.storageId]), so the order follows channels across slots.
|
||||
class ChannelOrderStore {
|
||||
static const String _keyPrefix = 'channel_order_';
|
||||
|
||||
@@ -12,53 +13,31 @@ class ChannelOrderStore {
|
||||
|
||||
String get keyFor => '$_keyPrefix$publicKeyHex';
|
||||
|
||||
Future<void> saveChannelOrder(List<int> order) async {
|
||||
Future<void> saveChannelOrder(List<String> order) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn('Public key hex is not set. Cannot save channel order.');
|
||||
return;
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
await prefs.setString(keyFor, jsonEncode(order));
|
||||
await PrefsManager.instance.setString(keyFor, jsonEncode(order));
|
||||
}
|
||||
|
||||
Future<List<int>> loadChannelOrder() async {
|
||||
Future<List<String>> loadChannelOrder() async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn('Public key hex is not set. Cannot load channel order.');
|
||||
return [];
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
String? jsonString = prefs.getString(keyFor);
|
||||
if ((jsonString == null || jsonString.isEmpty) &&
|
||||
canMigrateLegacyKeys(publicKeyHex)) {
|
||||
// Attempt migration from legacy unscoped key on first load
|
||||
final legacyJsonString = prefs.getString(_keyPrefix);
|
||||
prefs.remove(_keyPrefix);
|
||||
if (legacyJsonString != null && legacyJsonString.isNotEmpty) {
|
||||
appLogger.info(
|
||||
'Migrating channel order from legacy key $_keyPrefix to scoped key $keyFor',
|
||||
);
|
||||
await prefs.setString(keyFor, legacyJsonString);
|
||||
jsonString = legacyJsonString;
|
||||
}
|
||||
}
|
||||
final jsonString = PrefsManager.instance.getString(keyFor);
|
||||
if (jsonString == null || jsonString.isEmpty) {
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
final decoded = jsonDecode(jsonString);
|
||||
if (decoded is List) {
|
||||
return decoded
|
||||
.map((value) => value is int ? value : int.tryParse('$value'))
|
||||
.whereType<int>()
|
||||
.toList();
|
||||
return decoded.whereType<String>().toList();
|
||||
}
|
||||
} catch (_) {
|
||||
// fall through to legacy parse
|
||||
// Unreadable order: fall back to slot order.
|
||||
}
|
||||
return jsonString
|
||||
.split(',')
|
||||
.map((value) => int.tryParse(value))
|
||||
.whereType<int>()
|
||||
.toList();
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -43,30 +43,31 @@ class ChannelRegionStore {
|
||||
await PrefsManager.instance.setString(_defaultKey, region);
|
||||
}
|
||||
|
||||
Future<String> loadRegion(int channelIndex) async {
|
||||
String _keyForChannel(String channelId) => '${keyFor}_$channelId';
|
||||
|
||||
Future<String> loadRegion(String channelId) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn(
|
||||
'Public key hex is not set. Cannot load channel settings.',
|
||||
);
|
||||
return '';
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$keyFor$channelIndex';
|
||||
String? region = prefs.getString(key);
|
||||
return region ?? '';
|
||||
return PrefsManager.instance.getString(_keyForChannel(channelId)) ?? '';
|
||||
}
|
||||
|
||||
Future<String> saveRegion(int channelIndex, String region) async {
|
||||
Future<String> saveRegion(String channelId, String region) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn(
|
||||
'Public key hex is not set. Cannot save channel settings.',
|
||||
);
|
||||
return '';
|
||||
}
|
||||
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$keyFor$channelIndex';
|
||||
await prefs.setString(key, region);
|
||||
await PrefsManager.instance.setString(_keyForChannel(channelId), region);
|
||||
return region;
|
||||
}
|
||||
|
||||
Future<void> clearRegion(String channelId) async {
|
||||
if (publicKeyHex.isEmpty) return;
|
||||
await PrefsManager.instance.remove(_keyForChannel(channelId));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import '../utils/app_logger.dart';
|
||||
import 'legacy_key_migration.dart';
|
||||
import 'prefs_manager.dart';
|
||||
|
||||
class ChannelSettingsStore {
|
||||
@@ -15,105 +14,83 @@ class ChannelSettingsStore {
|
||||
String get keyForCyr2Lat => '$_cyr2latKeyPrefix$publicKeyHex';
|
||||
String get keyForUrlImages => '$_urlImagesKeyPrefix$publicKeyHex';
|
||||
|
||||
Future<bool> loadSmazEnabled(int channelIndex) async {
|
||||
String _smazKey(String channelId) => '${keyFor}_$channelId';
|
||||
String _cyr2LatKey(String channelId) => '${keyForCyr2Lat}_$channelId';
|
||||
String _cyr2LatProfileKey(String channelId) =>
|
||||
'${keyForCyr2Lat}_profile_$channelId';
|
||||
String _urlImagesKey(String channelId) => '${keyForUrlImages}_$channelId';
|
||||
|
||||
Future<bool> loadSmazEnabled(String channelId) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn(
|
||||
'Public key hex is not set. Cannot load channel settings.',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$keyFor$channelIndex';
|
||||
final oldKey = '$_keyPrefix$channelIndex';
|
||||
bool? enabled = prefs.getBool(key);
|
||||
if (enabled == null && canMigrateLegacyKeys(publicKeyHex)) {
|
||||
// Attempt migration from legacy unscoped key on first load
|
||||
enabled = prefs.getBool(oldKey);
|
||||
prefs.remove(oldKey);
|
||||
if (enabled != null) {
|
||||
appLogger.info(
|
||||
'Migrating channel settings from legacy key $oldKey to scoped key $key',
|
||||
);
|
||||
await prefs.setBool(key, enabled);
|
||||
}
|
||||
}
|
||||
return enabled ?? false;
|
||||
return PrefsManager.instance.getBool(_smazKey(channelId)) ?? false;
|
||||
}
|
||||
|
||||
Future<void> saveSmazEnabled(int channelIndex, bool enabled) async {
|
||||
Future<void> saveSmazEnabled(String channelId, bool enabled) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn(
|
||||
'Public key hex is not set. Cannot save channel settings.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$keyFor$channelIndex';
|
||||
await prefs.setBool(key, enabled);
|
||||
await PrefsManager.instance.setBool(_smazKey(channelId), enabled);
|
||||
}
|
||||
|
||||
Future<bool> loadCyr2LatEnabled(int channelIndex) async {
|
||||
Future<bool> loadCyr2LatEnabled(String channelId) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn(
|
||||
'Public key hex is not set. Cannot load channel Cyr2Lat settings.',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$keyForCyr2Lat$channelIndex';
|
||||
return prefs.getBool(key) ?? false;
|
||||
return PrefsManager.instance.getBool(_cyr2LatKey(channelId)) ?? false;
|
||||
}
|
||||
|
||||
Future<void> saveCyr2LatEnabled(int channelIndex, bool enabled) async {
|
||||
Future<void> saveCyr2LatEnabled(String channelId, bool enabled) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn(
|
||||
'Public key hex is not set. Cannot save channel Cyr2Lat settings.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$keyForCyr2Lat$channelIndex';
|
||||
await prefs.setBool(key, enabled);
|
||||
await PrefsManager.instance.setBool(_cyr2LatKey(channelId), enabled);
|
||||
}
|
||||
|
||||
Future<bool> loadUrlImagesEnabled(int channelIndex) async {
|
||||
Future<bool> loadUrlImagesEnabled(String channelId) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn(
|
||||
'Public key hex is not set. Cannot load channel URL image settings.',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$keyForUrlImages$channelIndex';
|
||||
return prefs.getBool(key) ?? false;
|
||||
return PrefsManager.instance.getBool(_urlImagesKey(channelId)) ?? false;
|
||||
}
|
||||
|
||||
Future<void> saveUrlImagesEnabled(int channelIndex, bool enabled) async {
|
||||
Future<void> saveUrlImagesEnabled(String channelId, bool enabled) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn(
|
||||
'Public key hex is not set. Cannot save channel URL image settings.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
await PrefsManager.instance.setBool(
|
||||
'$keyForUrlImages$channelIndex',
|
||||
enabled,
|
||||
);
|
||||
await PrefsManager.instance.setBool(_urlImagesKey(channelId), enabled);
|
||||
}
|
||||
|
||||
Future<String?> loadCyr2LatProfileId(int channelIndex) async {
|
||||
Future<String?> loadCyr2LatProfileId(String channelId) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn(
|
||||
'Public key hex is not set. Cannot load channel settings.',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '${keyForCyr2Lat}profile_$channelIndex';
|
||||
return prefs.getString(key);
|
||||
return PrefsManager.instance.getString(_cyr2LatProfileKey(channelId));
|
||||
}
|
||||
|
||||
Future<void> saveCyr2LatProfileId(int channelIndex, String? profileId) async {
|
||||
Future<void> saveCyr2LatProfileId(String channelId, String? profileId) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn(
|
||||
'Public key hex is not set. Cannot save channel settings.',
|
||||
@@ -121,11 +98,21 @@ class ChannelSettingsStore {
|
||||
return;
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '${keyForCyr2Lat}profile_$channelIndex';
|
||||
final key = _cyr2LatProfileKey(channelId);
|
||||
if (profileId == null) {
|
||||
await prefs.remove(key);
|
||||
} else {
|
||||
await prefs.setString(key, profileId);
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes every setting stored for [channelId].
|
||||
Future<void> clearChannel(String channelId) async {
|
||||
if (publicKeyHex.isEmpty) return;
|
||||
final prefs = PrefsManager.instance;
|
||||
await prefs.remove(_smazKey(channelId));
|
||||
await prefs.remove(_cyr2LatKey(channelId));
|
||||
await prefs.remove(_cyr2LatProfileKey(channelId));
|
||||
await prefs.remove(_urlImagesKey(channelId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import '../utils/app_logger.dart';
|
||||
import 'channel_message_store.dart';
|
||||
import 'channel_store.dart';
|
||||
import 'legacy_key_migration.dart';
|
||||
import 'prefs_manager.dart';
|
||||
|
||||
/// One-shot move of a radio's per-channel data from slot-index keys
|
||||
/// (`<prefix><scope><slot>`) to channel-ID keys (`<prefix><scope>_<id>`).
|
||||
///
|
||||
/// The slot -> PSK mapping comes from the radio's cached channel list, which is
|
||||
/// the mapping the legacy data was written under. Legacy keys of slots with no
|
||||
/// cached PSK are left alone and never read again.
|
||||
class ChannelStorageMigration {
|
||||
static const String _doneKeyPrefix = 'channel_storage_v2_';
|
||||
|
||||
static const String _messagesPrefix = 'channel_messages_';
|
||||
static const String _smazPrefix = 'channel_smaz_';
|
||||
static const String _cyr2latPrefix = 'channel_cyr2lat_';
|
||||
static const String _urlImagesPrefix = 'channel_url_images_';
|
||||
static const String _regionPrefix = 'channel_region_';
|
||||
static const String _orderPrefix = 'channel_order_';
|
||||
|
||||
/// Migrates [scope] (first 10 hex chars of the radio's public key) and
|
||||
/// returns the slot -> channel ID mapping it used. Returns an empty map when
|
||||
/// the scope was already migrated or must not adopt legacy data.
|
||||
static Future<Map<int, String>> migrate(String scope) async {
|
||||
if (scope.isEmpty || !canMigrateLegacyKeys(scope)) return {};
|
||||
final prefs = PrefsManager.instance;
|
||||
final doneKey = '$_doneKeyPrefix$scope';
|
||||
if (prefs.getBool(doneKey) == true) return {};
|
||||
|
||||
final channelStore = ChannelStore()..setPublicKeyHex = scope;
|
||||
final cached = await channelStore.loadChannels();
|
||||
final slotIds = <int, String>{};
|
||||
for (final channel in cached) {
|
||||
final id = channel.storageId;
|
||||
if (id != null) slotIds[channel.index] = id;
|
||||
}
|
||||
|
||||
final slots = slotIds.keys.toList()..sort();
|
||||
for (final slot in slots) {
|
||||
final id = slotIds[slot]!;
|
||||
await _moveMessages(scope, slot, id);
|
||||
await _moveBool(
|
||||
'$_smazPrefix$scope',
|
||||
slot,
|
||||
id,
|
||||
legacyPrefix: _smazPrefix,
|
||||
);
|
||||
await _moveBool('$_cyr2latPrefix$scope', slot, id);
|
||||
await _moveBool('$_urlImagesPrefix$scope', slot, id);
|
||||
await _moveString(
|
||||
'$_cyr2latPrefix${scope}profile_$slot',
|
||||
'$_cyr2latPrefix${scope}_profile_$id',
|
||||
);
|
||||
await _moveString(
|
||||
'$_regionPrefix$scope$slot',
|
||||
'$_regionPrefix${scope}_$id',
|
||||
);
|
||||
}
|
||||
await _migrateOrder(scope, slotIds);
|
||||
|
||||
await prefs.setBool(doneKey, true);
|
||||
await channelStore.saveSlotChannelIds(slotIds);
|
||||
if (slotIds.isNotEmpty) {
|
||||
appLogger.info(
|
||||
'Moved channel data for ${slotIds.length} slots of $scope to channel IDs',
|
||||
);
|
||||
}
|
||||
return slotIds;
|
||||
}
|
||||
|
||||
static Future<void> _moveMessages(String scope, int slot, String id) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final oldKey = '$_messagesPrefix$scope$slot';
|
||||
final legacyKey = '$_messagesPrefix$slot';
|
||||
final newKey = '$_messagesPrefix${scope}_$id';
|
||||
var json = prefs.getString(oldKey);
|
||||
if (json == null || json.isEmpty) json = prefs.getString(legacyKey);
|
||||
if (json != null && json.isNotEmpty) {
|
||||
final existing = prefs.getString(newKey);
|
||||
// Two slots holding the same PSK now share one history.
|
||||
await prefs.setString(
|
||||
newKey,
|
||||
existing == null || existing.isEmpty
|
||||
? json
|
||||
: _mergeMessages(existing, json),
|
||||
);
|
||||
}
|
||||
// Old keys go only after the new one is written, so an interrupted run
|
||||
// loses nothing; the next launch repeats it.
|
||||
await prefs.remove(oldKey);
|
||||
await prefs.remove(legacyKey);
|
||||
}
|
||||
|
||||
static String _mergeMessages(String a, String b) {
|
||||
try {
|
||||
// A rerun after an interrupted migration merges a history into
|
||||
// itself, so drop entries already present.
|
||||
final seen = <String>{};
|
||||
final merged =
|
||||
[...jsonDecode(a) as List<dynamic>, ...jsonDecode(b) as List<dynamic>]
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.where((m) => seen.add(_mergeKey(m)))
|
||||
.toList();
|
||||
merged.sort(
|
||||
(x, y) => ((x['timestamp'] as int?) ?? 0).compareTo(
|
||||
(y['timestamp'] as int?) ?? 0,
|
||||
),
|
||||
);
|
||||
final overflow = merged.length - ChannelMessageStore.maxStoredMessages;
|
||||
if (overflow > 0) merged.removeRange(0, overflow);
|
||||
return jsonEncode(merged);
|
||||
} catch (_) {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
|
||||
static String _mergeKey(Map<String, dynamic> json) {
|
||||
final messageId = json['messageId'];
|
||||
if (messageId is String && messageId.isNotEmpty) return 'id:$messageId';
|
||||
return 'fallback:${json['timestamp']}:${json['senderName']}:${json['text']}';
|
||||
}
|
||||
|
||||
static Future<void> _moveBool(
|
||||
String scopedPrefix,
|
||||
int slot,
|
||||
String id, {
|
||||
String? legacyPrefix,
|
||||
}) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final oldKey = '$scopedPrefix$slot';
|
||||
final newKey = '${scopedPrefix}_$id';
|
||||
final legacyKey = legacyPrefix == null ? null : '$legacyPrefix$slot';
|
||||
var value = prefs.get(oldKey);
|
||||
if (value == null && legacyKey != null) value = prefs.get(legacyKey);
|
||||
if (value is bool && !prefs.containsKey(newKey)) {
|
||||
await prefs.setBool(newKey, value);
|
||||
}
|
||||
await prefs.remove(oldKey);
|
||||
if (legacyKey != null) await prefs.remove(legacyKey);
|
||||
}
|
||||
|
||||
static Future<void> _moveString(String oldKey, String newKey) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final value = prefs.get(oldKey);
|
||||
if (value is String && !prefs.containsKey(newKey)) {
|
||||
await prefs.setString(newKey, value);
|
||||
}
|
||||
await prefs.remove(oldKey);
|
||||
}
|
||||
|
||||
static Future<void> _migrateOrder(
|
||||
String scope,
|
||||
Map<int, String> slotIds,
|
||||
) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$_orderPrefix$scope';
|
||||
var raw = prefs.getString(key);
|
||||
if (raw == null || raw.isEmpty) raw = prefs.getString(_orderPrefix);
|
||||
if (raw == null || raw.isEmpty) return;
|
||||
final slots = <int>[];
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is List) {
|
||||
// String entries are channel IDs from an interrupted earlier run.
|
||||
if (decoded.any((value) => value is String)) return;
|
||||
slots.addAll(decoded.whereType<int>());
|
||||
} else if (decoded is int) {
|
||||
// A one-slot legacy comma-separated list parses as a bare number.
|
||||
slots.add(decoded);
|
||||
}
|
||||
} catch (_) {
|
||||
slots.addAll(raw.split(',').map(int.tryParse).whereType<int>());
|
||||
}
|
||||
final ids = <String>[];
|
||||
for (final slot in slots) {
|
||||
final id = slotIds[slot];
|
||||
if (id != null && !ids.contains(id)) ids.add(id);
|
||||
}
|
||||
await prefs.setString(key, jsonEncode(ids));
|
||||
await prefs.remove(_orderPrefix);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import 'prefs_manager.dart';
|
||||
|
||||
class ChannelStore {
|
||||
static const String _keyPrefix = 'channels';
|
||||
static const String _slotIdsKeyPrefix = 'channel_slot_ids_';
|
||||
String publicKeyHex = '';
|
||||
set setPublicKeyHex(String value) =>
|
||||
publicKeyHex = value.length >= 10 ? value.substring(0, 10) : '';
|
||||
@@ -70,6 +71,38 @@ class ChannelStore {
|
||||
await prefs.setString(keyFor, jsonEncode(jsonList));
|
||||
}
|
||||
|
||||
String get _slotIdsKey => '$_slotIdsKeyPrefix$publicKeyHex';
|
||||
|
||||
/// The slot -> [Channel.storageId] map confirmed by the last channel sync,
|
||||
/// used to spot slots another app changed while we were away.
|
||||
Future<Map<int, String>> loadSlotChannelIds() async {
|
||||
if (publicKeyHex.isEmpty) return {};
|
||||
final jsonString = PrefsManager.instance.getString(_slotIdsKey);
|
||||
if (jsonString == null || jsonString.isEmpty) return {};
|
||||
try {
|
||||
final decoded = jsonDecode(jsonString);
|
||||
if (decoded is! Map) return {};
|
||||
final ids = <int, String>{};
|
||||
for (final entry in decoded.entries) {
|
||||
final slot = int.tryParse('${entry.key}');
|
||||
final id = entry.value;
|
||||
if (slot != null && id is String && id.isNotEmpty) ids[slot] = id;
|
||||
}
|
||||
return ids;
|
||||
} catch (e) {
|
||||
appLogger.warn('Stored channel slot map is unreadable: $e');
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> saveSlotChannelIds(Map<int, String> ids) async {
|
||||
if (publicKeyHex.isEmpty) return;
|
||||
await PrefsManager.instance.setString(
|
||||
_slotIdsKey,
|
||||
jsonEncode({for (final e in ids.entries) '${e.key}': e.value}),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> _toJson(Channel channel) {
|
||||
return {
|
||||
'index': channel.index,
|
||||
|
||||
Reference in new issue
Block a user