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:
zjs81 committed 2026-10-11 17:52:59 -07:00
1 parent d30744aa31
commit 679116ed03
24 files changed
+1794 -340

No files matched your search

File diff suppressed because it is too large. Load diff
+17 -8
View File
@@ -109,7 +109,10 @@ void main() async {
// Availability/isBusy changes are the only thing that un-parks a decode
// queue that stopped because the codec was unusable or busy.
imageCodecService.addListener(receivedImageStore.notifyDecoderChanged);
final imageReassembler = ImageStreamReassembler(store: receivedImageStore);
final imageReassembler = ImageStreamReassembler(
store: receivedImageStore,
channelIdForSlot: connector.channelIdForSlot,
);
final imageTransport = ImageChunkTransport(
reassembler: imageReassembler,
// The UI sends whole chunk sets through connector.sendImageChunks so it
@@ -158,6 +161,7 @@ void main() async {
timeoutPredictionService: timeoutPredictionService,
imageCodecService: imageCodecService,
imageTransport: imageTransport,
receivedImageStore: receivedImageStore,
// ImageStreamReassembler.addChunk already forwards every outcome to the
// store together with the channel index (which ImageChunkOutcome itself
// does not carry), so onImageChunk would be a second, channel-blind path.
@@ -165,11 +169,7 @@ void main() async {
);
await connector.loadContactCache();
await connector.loadChannelSettings();
await connector.loadCachedChannels();
// Load persisted channel messages
await connector.loadAllChannelMessages();
await connector.loadUnreadState();
runApp(
@@ -251,7 +251,7 @@ class AppSettingsImageCodecStore implements ImageCodecSettingsStore {
/// An [ImageReassembler] that (a) learns the local sender prefix after
/// SELF_INFO and (b) forwards every outcome to [ReceivedImageStore] together
/// with the channel index.
/// with the channel index and the channel ID that slot holds.
///
/// Both exist because of upstream shapes this file cannot change:
/// * `ImageReassembler.selfPrefix` is `final`, but the local public key does
@@ -265,9 +265,12 @@ class AppSettingsImageCodecStore implements ImageCodecSettingsStore {
class ImageStreamReassembler extends ImageReassembler {
final ReceivedImageStore store;
/// Resolves the radio slot a chunk arrived on to its [Channel.storageId].
final String? Function(int channelIndex)? channelIdForSlot;
int? _selfPrefix;
ImageStreamReassembler({required this.store})
ImageStreamReassembler({required this.store, this.channelIdForSlot})
: super(onFailed: ((failure) => unawaited(store.handleFailure(failure))));
@override
@@ -282,7 +285,13 @@ class ImageStreamReassembler extends ImageReassembler {
DateTime? now,
}) {
final outcome = super.addChunk(blob, channelIndex: channelIndex, now: now);
unawaited(store.handleOutcome(outcome, channelIndex: channelIndex));
unawaited(
store.handleOutcome(
outcome,
channelIndex: channelIndex,
channelId: channelIdForSlot?.call(channelIndex),
),
);
return outcome;
}
}
+19
View File
@@ -25,6 +25,25 @@ class Channel {
bool get isEmpty => name.isEmpty && psk.every((b) => b == 0);
/// Key for this channel's persisted data (messages, settings, region,
/// order, images). Derived from the PSK so it follows the channel across
/// radio slots; null for an empty slot.
late final String? storageId = storageIdForPsk(psk);
static const String _storageIdDomain = 'meshcore-channel:';
/// First 8 bytes of SHA-256("meshcore-channel:" + psk) as 16 hex chars, or
/// null for an all-zero PSK. Not the 1-byte on-air channel hash, which
/// collides.
static String? storageIdForPsk(Uint8List psk) {
if (psk.every((b) => b == 0)) return null;
final digest = crypto.sha256.convert([
...utf8.encode(_storageIdDomain),
...psk,
]);
return _bytesToHex(Uint8List.fromList(digest.bytes.sublist(0, 8)));
}
/// Key used for per-channel notification muting.
String get muteKey => name.isEmpty ? 'Channel $index' : name;
+2 -1
View File
@@ -124,6 +124,7 @@ class ChannelMessage {
MessageTranslationStatus? translationStatus,
Object? translationModelId = _unset,
Map<String, List<String?>>? reactions,
int? channelIndex,
}) {
return ChannelMessage(
senderKey: senderKey,
@@ -152,7 +153,7 @@ class ChannelMessage {
pathHashWidth: pathHashWidth ?? this.pathHashWidth,
pathBytes: pathBytes ?? this.pathBytes,
pathVariants: pathVariants ?? this.pathVariants,
channelIndex: channelIndex,
channelIndex: channelIndex ?? this.channelIndex,
region: region == _unset ? this.region : region as String?,
messageId: messageId,
packetHash: packetHash ?? this.packetHash,
+6 -6
View File
@@ -1514,6 +1514,7 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
try {
await store.registerOutgoing(
channelIndex: widget.channel.index,
channelId: widget.channel.storageId,
// The same 16 bits the chunk header carries, so the entry keys the
// same way an inbound one would.
senderPrefix: senderPrefix,
@@ -1629,10 +1630,7 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
}
final images = store == null
? const <ReceivedImageEntry>[]
: [
for (final entry in store.entries)
if (entry.channelIndex == widget.channel.index) entry,
];
: store.entriesForChannel(widget.channel.storageId);
final layout = _TranscriptLayout.build(
messages: messages,
images: images,
@@ -2339,9 +2337,11 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
context.read<MeshCoreConnector>().clearMessagesForChannel(
widget.channel.index,
);
final channelId = widget.channel.storageId;
if (channelId == null) return;
try {
await context.read<ReceivedImageStore>().deleteImagesForChannel(
widget.channel.index,
await context.read<ReceivedImageStore>().deleteImagesForChannelId(
channelId,
);
} on ProviderNotFoundException {
return;
+11 -56
View File
@@ -2,7 +2,6 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/utils/keys.dart';
import 'package:meshcore_open/utils/platform_info.dart';
import 'package:meshcore_open/widgets/app_bar.dart';
@@ -12,7 +11,6 @@ import 'package:uuid/uuid.dart';
import '../connector/meshcore_connector.dart';
import '../l10n/l10n.dart';
import '../services/app_settings_service.dart';
import '../services/received_image_store.dart';
import '../services/ui_view_state_service.dart';
import '../models/channel.dart';
import '../models/community.dart';
@@ -55,8 +53,6 @@ class _ChannelsScreenState extends State<ChannelsScreen>
List<Community> _communities = [];
Timer? _searchDebounce;
ChannelMessageStore get _channelMessageStore => ChannelMessageStore();
@override
void initState() {
super.initState();
@@ -102,9 +98,6 @@ class _ChannelsScreenState extends State<ChannelsScreen>
final connector = context.watch<MeshCoreConnector>();
final viewState = context.watch<UiViewStateService>();
final channelMessageStore = ChannelMessageStore();
channelMessageStore.setPublicKeyHex = connector.selfPublicKeyHex;
// Auto-navigate back to scanner if disconnected
if (!checkConnectionAndNavigate(connector)) {
return const SizedBox.shrink();
@@ -316,7 +309,6 @@ class _ChannelsScreenState extends State<ChannelsScreen>
return _buildChannelTile(
context,
connector,
channelMessageStore,
channel,
showDragHandle: true,
dragIndex: index,
@@ -337,7 +329,6 @@ class _ChannelsScreenState extends State<ChannelsScreen>
return _buildChannelTile(
context,
connector,
channelMessageStore,
channel,
listIndex: index,
);
@@ -373,7 +364,6 @@ class _ChannelsScreenState extends State<ChannelsScreen>
Widget _buildChannelTile(
BuildContext context,
MeshCoreConnector connector,
ChannelMessageStore channelMessageStore,
Channel channel, {
bool showDragHandle = false,
int? dragIndex,
@@ -467,19 +457,10 @@ class _ChannelsScreenState extends State<ChannelsScreen>
),
);
},
onLongPress: () => _showChannelActions(
this.context,
connector,
channelMessageStore,
channel,
),
onLongPress: () =>
_showChannelActions(this.context, connector, channel),
onSecondaryTap: PlatformInfo.isDesktop
? () => _showChannelActions(
this.context,
connector,
channelMessageStore,
channel,
)
? () => _showChannelActions(this.context, connector, channel)
: null,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -639,7 +620,6 @@ class _ChannelsScreenState extends State<ChannelsScreen>
void _showChannelActions(
BuildContext context,
MeshCoreConnector connector,
ChannelMessageStore channelMessageStore,
Channel channel,
) {
final parentContext = context;
@@ -698,12 +678,7 @@ class _ChannelsScreenState extends State<ChannelsScreen>
Navigator.pop(sheetContext);
await Future.delayed(const Duration(milliseconds: 100));
if (parentContext.mounted) {
_confirmDeleteChannel(
parentContext,
connector,
channelMessageStore,
channel,
);
_confirmDeleteChannel(parentContext, connector, channel);
}
},
),
@@ -949,9 +924,7 @@ class _ChannelsScreenState extends State<ChannelsScreen>
);
}
Widget? buildExpandedContent(
ChannelMessageStore channelMessageStore,
) {
Widget? buildExpandedContent() {
switch (selectedOption) {
case 0: // Create Private Channel
return Column(
@@ -1005,8 +978,6 @@ class _ChannelsScreenState extends State<ChannelsScreen>
name,
psk,
);
await channelMessageStore
.clearChannelMessages(nextIndex);
if (context.mounted) {
showDismissibleSnackBar(
context,
@@ -1607,8 +1578,7 @@ class _ChannelsScreenState extends State<ChannelsScreen>
.l10n
.channels_joinPublicChannelDesc,
),
if (selectedOption == 2)
buildExpandedContent(_channelMessageStore)!,
if (selectedOption == 2) buildExpandedContent()!,
],
buildOptionCard(
optionIndex: 3,
@@ -1619,8 +1589,7 @@ class _ChannelsScreenState extends State<ChannelsScreen>
.l10n
.channels_joinHashtagChannelDesc,
),
if (selectedOption == 3)
buildExpandedContent(_channelMessageStore)!,
if (selectedOption == 3) buildExpandedContent()!,
buildOptionCard(
optionIndex: 1,
icon: Icons.lock,
@@ -1630,16 +1599,14 @@ class _ChannelsScreenState extends State<ChannelsScreen>
.l10n
.channels_joinPrivateChannelDesc,
),
if (selectedOption == 1)
buildExpandedContent(_channelMessageStore)!,
if (selectedOption == 1) buildExpandedContent()!,
buildOptionCard(
optionIndex: 4,
icon: Icons.qr_code_scanner,
title: sheetContext.l10n.community_scanQr,
subtitle: sheetContext.l10n.community_join,
),
if (selectedOption == 4)
buildExpandedContent(_channelMessageStore)!,
if (selectedOption == 4) buildExpandedContent()!,
SectionHeader(
sheetContext.l10n.channels_addSectionCreate,
),
@@ -1652,16 +1619,14 @@ class _ChannelsScreenState extends State<ChannelsScreen>
.l10n
.channels_createPrivateChannelDesc,
),
if (selectedOption == 0)
buildExpandedContent(_channelMessageStore)!,
if (selectedOption == 0) buildExpandedContent()!,
buildOptionCard(
optionIndex: 5,
icon: Icons.groups,
title: sheetContext.l10n.community_create,
subtitle: sheetContext.l10n.community_createDesc,
),
if (selectedOption == 5)
buildExpandedContent(_channelMessageStore)!,
if (selectedOption == 5) buildExpandedContent()!,
],
),
),
@@ -1914,15 +1879,8 @@ class _ChannelsScreenState extends State<ChannelsScreen>
void _confirmDeleteChannel(
BuildContext context,
MeshCoreConnector connector,
ChannelMessageStore channelMessageStore,
Channel channel,
) {
ReceivedImageStore? imageStore;
try {
imageStore = context.read<ReceivedImageStore>();
} on ProviderNotFoundException {
imageStore = null;
}
final channelLabel = channel.name.isEmpty
? context.l10n.channels_channelIndex(channel.index)
: channel.name;
@@ -1944,9 +1902,6 @@ class _ChannelsScreenState extends State<ChannelsScreen>
try {
await connector.deleteChannel(channel.index);
await channelMessageStore.clearChannelMessages(channel.index);
await imageStore?.deleteImagesForChannel(channel.index);
if (!context.mounted) return;
showDismissibleSnackBar(
+32
View File
@@ -633,6 +633,10 @@ enum ImageReassemblyFailureReason {
/// Dropped by [ImageReassembler.clear] (disconnect / new session).
disconnected,
/// Dropped by [ImageReassembler.clearChannel] because the radio slot it
/// arrived on now holds a different channel.
channelChanged,
}
/// A fully reassembled image.
@@ -878,6 +882,34 @@ class ImageReassembler {
}
}
/// Drops every stream that arrived on [channelIndex], whose radio slot now
/// holds a different channel, so a new image there can never be completed
/// with the old channel's bytes. In-progress streams are reported through
/// [onFailed] so their bubbles stop showing "receiving".
void clearChannel(int channelIndex, {DateTime? now}) {
final at = now ?? _clock();
_recentlyCompleted.removeWhere(
(key, _) => key.channelIndex == channelIndex,
);
final dropped = _pending.values
.where((entry) => entry.key.channelIndex == channelIndex)
.toList();
for (final entry in dropped) {
_pending.remove(entry.key);
onFailed?.call(
ImageReassemblyFailure(
key: entry.key,
total: entry.total,
receivedDataChunks: entry.bodies.length,
hadParity: entry.hasParity,
firstSeen: entry.firstSeen,
expiredAt: at,
reason: ImageReassemblyFailureReason.channelChanged,
),
);
}
}
/// Feeds one received GRP_DATA blob.
///
/// [now] overrides the clock for tests. Expired entries are swept first, so
+50 -3
View File
@@ -159,6 +159,11 @@ class ReceivedImageEntry {
final int imgId;
final int channelIndex;
/// [Channel.storageId] of the channel the image belongs to. [channelIndex]
/// is the radio slot it arrived on, which another channel may reuse later.
/// Null only for entries written before channel IDs existed.
final String? channelId;
/// Local clock at the first chunk — code 27 carries no timestamp.
final DateTime firstSeen;
@@ -221,6 +226,7 @@ class ReceivedImageEntry {
required this.senderPrefix,
required this.imgId,
required this.channelIndex,
this.channelId,
required this.firstSeen,
required this.state,
required this.receivedChunks,
@@ -259,6 +265,7 @@ class ReceivedImageEntry {
static const Object _unset = Object();
ReceivedImageEntry copyWith({
String? channelId,
ReceivedImageState? state,
int? receivedChunks,
int? totalChunks,
@@ -281,6 +288,7 @@ class ReceivedImageEntry {
senderPrefix: senderPrefix,
imgId: imgId,
channelIndex: channelIndex,
channelId: channelId ?? this.channelId,
firstSeen: firstSeen,
state: state ?? this.state,
receivedChunks: receivedChunks ?? this.receivedChunks,
@@ -309,6 +317,7 @@ class ReceivedImageEntry {
'senderPrefix': senderPrefix,
'imgId': imgId,
'channelIndex': channelIndex,
if (channelId != null) 'channelId': channelId,
'firstSeenMs': firstSeen.millisecondsSinceEpoch,
'state': state.name,
'receivedChunks': receivedChunks,
@@ -335,6 +344,7 @@ class ReceivedImageEntry {
senderPrefix: json['senderPrefix'] as int? ?? 0,
imgId: json['imgId'] as int? ?? 0,
channelIndex: json['channelIndex'] as int? ?? 0,
channelId: json['channelId'] as String?,
firstSeen: DateTime.fromMillisecondsSinceEpoch(
json['firstSeenMs'] as int? ?? 0,
),
@@ -760,6 +770,7 @@ class ReceivedImageStore extends ChangeNotifier {
Future<ReceivedImageEntry?> handleOutcome(
ImageChunkOutcome outcome, {
required int channelIndex,
String? channelId,
DateTime? at,
}) async {
final now = at ?? _clock();
@@ -810,6 +821,8 @@ class ReceivedImageStore extends ChangeNotifier {
.toInt(),
totalChunks: header.total,
error: null,
// A first chunk seen before its slot had an ID gets one now.
channelId: existing.channelId ?? channelId,
);
return _store(updated);
}
@@ -826,6 +839,7 @@ class ReceivedImageStore extends ChangeNotifier {
senderPrefix: header.senderPrefix,
imgId: header.imgId,
channelIndex: channelIndex,
channelId: channelId,
firstSeen: now,
state: ReceivedImageState.receiving,
receivedChunks: counts,
@@ -861,13 +875,14 @@ class ReceivedImageStore extends ChangeNotifier {
case ImageChunkStatus.completed:
final result = outcome.result;
if (result == null) return null;
return _handleCompleted(result, now);
return _handleCompleted(result, now, channelId);
}
}
Future<ReceivedImageEntry> _handleCompleted(
ImageReassemblyResult result,
DateTime now,
String? channelId,
) async {
final key = result.key;
var entry = entryForKey(key);
@@ -884,11 +899,14 @@ class ReceivedImageStore extends ChangeNotifier {
senderPrefix: key.senderPrefix,
imgId: key.imgId,
channelIndex: key.channelIndex,
channelId: channelId,
firstSeen: now,
state: ReceivedImageState.receiving,
receivedChunks: result.chunkCount,
totalChunks: result.chunkCount,
);
} else if (entry.channelId == null && channelId != null) {
entry = entry.copyWith(channelId: channelId);
}
final metadata = result.metadata;
@@ -1000,6 +1018,7 @@ class ReceivedImageStore extends ChangeNotifier {
/// ```dart
/// final entry = await receivedImageStore.registerOutgoing(
/// channelIndex: channelIndex,
/// channelId: channel.storageId,
/// senderPrefix: selfPrefix, // same 16 bits the chunk header carries
/// imgId: chunkSet.imgId,
/// previewPng: preview.croppedPngBytes, // the 512x512 crop, NOT a decode
@@ -1015,6 +1034,7 @@ class ReceivedImageStore extends ChangeNotifier {
/// memory beyond the encode that already ran.
Future<ReceivedImageEntry> registerOutgoing({
required int channelIndex,
String? channelId,
required int senderPrefix,
required int imgId,
required Uint8List previewPng,
@@ -1038,6 +1058,7 @@ class ReceivedImageStore extends ChangeNotifier {
senderPrefix: senderPrefix,
imgId: imgId,
channelIndex: channelIndex,
channelId: channelId,
firstSeen: now,
state: ReceivedImageState.decoded,
receivedChunks: chunkCount,
@@ -1429,9 +1450,9 @@ class ReceivedImageStore extends ChangeNotifier {
///
/// Returns the stream ids that were removed, so the caller can strip their
/// sentinels from the channel's message list in one pass.
Future<List<String>> deleteImagesForChannel(int channelIndex) async {
Future<List<String>> deleteImagesForChannelId(String channelId) async {
final doomed = _entries.values
.where((e) => e.channelIndex == channelIndex)
.where((e) => e.channelId == channelId)
.map((e) => e.streamId)
.toList();
for (final streamId in doomed) {
@@ -1440,6 +1461,32 @@ class ReceivedImageStore extends ChangeNotifier {
return doomed;
}
/// Images of [channelId], newest first.
List<ReceivedImageEntry> entriesForChannel(String? channelId) {
if (channelId == null) return const <ReceivedImageEntry>[];
return entries.where((e) => e.channelId == channelId).toList();
}
/// Gives entries saved before channel IDs existed the ID of the channel
/// their slot held then ([slotIds], from the radio's cached channel list).
/// The store is app-wide, so with several radios the first one migrated
/// claims the unstamped images.
Future<void> stampLegacyChannelIds(Map<int, String> slotIds) async {
for (final entry in _entries.values.toList()) {
if (entry.channelId != null) continue;
final channelId = slotIds[entry.channelIndex];
if (channelId == null) continue;
await _store(entry.copyWith(channelId: channelId));
}
}
/// Forgets which in-progress streams arrived on [channelIndex] after the
/// radio slot was given to another channel, so a new image on that slot
/// never continues an old one.
void forgetChannelSlot(int channelIndex) {
_byKey.removeWhere((key, _) => key.channelIndex == channelIndex);
}
/// Deletes an image for each sentinel that is still present in a channel's
/// message list, and drops everything else this store holds for that channel.
///
+22 -46
View File
@@ -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);
}
+9 -30
View File
@@ -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 [];
}
}
+11 -10
View File
@@ -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));
}
}
+32 -45
View File
@@ -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));
}
}
+186
View File
@@ -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);
}
}
+33
View File
@@ -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,