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
@@ -198,13 +198,17 @@ UUID, name, 32-byte secret, hashtag channel list. Shared via QR code.
|
||||
|
||||
Message/contact metadata and preferences use `SharedPreferences` (JSON-serialized); there is no SQLite database. Model bundles, received image bitstreams/reconstructions, and map caches use files. Region metadata is persisted with channel messages; older records without it load with a null region.
|
||||
|
||||
Per-channel data is keyed by a channel ID, not the radio slot: `<channelId>` is the first 8 bytes of SHA-256(`"meshcore-channel:"` + PSK) as 16 hex characters, so a reused slot starts clean and a re-added channel gets its history back. Each channel sync saves the slot-to-ID map (`channel_slot_ids_<pubKey10>`) and reloads any slot whose channel changed since the last connection; queued channel messages are not fetched until that map is confirmed. Older slot-keyed data is moved once per radio (`channel_storage_v2_<pubKey10>`) using the cached channel list; slots with no cached PSK keep their old keys unread.
|
||||
|
||||
| Data | Storage Key Pattern | Scope |
|
||||
|---|---|---|
|
||||
| Contacts | `contacts<pubKey10>` | Per device identity |
|
||||
| Messages | `messages_<pubKey10><contactKey>` | Per device + contact |
|
||||
| Channel Messages | `channel_messages_<pubKey10><index>` | Per device + channel |
|
||||
| Channel Messages | `channel_messages_<pubKey10>_<channelId>` | Per device + channel |
|
||||
| Channels | `channels<pubKey10>` | Per device identity |
|
||||
| Channel Order | `channel_order_<pubKey10>` | Per device identity |
|
||||
| Channel Order | `channel_order_<pubKey10>` (list of channel IDs) | Per device identity |
|
||||
| Channel Slot Map | `channel_slot_ids_<pubKey10>` | Per device identity |
|
||||
| Channel Settings | `channel_{smaz,cyr2lat,url_images}_<pubKey10>_<channelId>`, `channel_cyr2lat_<pubKey10>_profile_<channelId>` | Per device + channel |
|
||||
| Contact Groups | `contact_groups<pubKey10>` | Per device identity |
|
||||
| Communities | `communities_v1<pubKey10>` | Per device identity |
|
||||
| Unread Counts | `contact_unread_count<pubKey10>` | Per device identity |
|
||||
@@ -212,7 +216,7 @@ Message/contact metadata and preferences use `SharedPreferences` (JSON-serialize
|
||||
| App Settings | `app_settings` | Global |
|
||||
| Path History | `path_history_<contactKey>` | Per contact |
|
||||
| Region Names | `regions` | Global |
|
||||
| Channel Region | `channel_region_<pubKey10><index>` | Per device + channel |
|
||||
| Channel Region | `channel_region_<pubKey10>_<channelId>` | Per device + channel |
|
||||
| Default Region | `default_region_<pubKey10>` | Per device identity |
|
||||
|
||||
## Auto-Add Configuration Bitmask
|
||||
|
||||
@@ -63,7 +63,9 @@ Name limits count the `#` and any community prefix, so the name stored on the ra
|
||||
|---|---|
|
||||
| Edit | Change name, PSK (with a dice icon to generate a random PSK), SMAZ compression toggle (compresses outgoing messages to allow longer text within the byte limit), Cyr2Lat encoding toggle (transliterates Cyrillic to Latin for compatibility), or "Enable URL images" toggle (previews image links; requires internet) |
|
||||
| Mute / Unmute | Toggle push notification suppression for this channel |
|
||||
| Delete | Remove the channel from the device (confirmation required) |
|
||||
| Delete | Remove the channel from the device and delete its messages, settings, region and images (confirmation required) |
|
||||
|
||||
Channel history and settings belong to the channel's key, not its slot on the radio. A slot reused for another channel (here or in another app) starts empty, editing a channel's PSK starts a fresh history, and adding a channel again with its old PSK brings its history back.
|
||||
|
||||
## Channel Chat
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+17
-8
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
///
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:crypto/crypto.dart' as crypto;
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/models/channel.dart';
|
||||
import 'package:meshcore_open/models/channel_message.dart';
|
||||
import 'package:meshcore_open/review_mode/review_frames.dart';
|
||||
import 'package:meshcore_open/review_mode/review_radio.dart';
|
||||
import 'package:meshcore_open/review_mode/review_script.dart';
|
||||
import 'package:meshcore_open/services/message_retry_service.dart';
|
||||
import 'package:meshcore_open/services/path_history_service.dart';
|
||||
import 'package:meshcore_open/services/storage_service.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:pointycastle/export.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
final _scope = ReviewRadio.storagePrefix;
|
||||
const _queuedHikingText = 'Planning to leave the trailhead at 8 on Saturday.';
|
||||
|
||||
Future<void> _waitFor(bool Function() condition, {int seconds = 8}) async {
|
||||
final end = DateTime.now().add(Duration(seconds: seconds));
|
||||
while (!condition()) {
|
||||
if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
}
|
||||
}
|
||||
|
||||
Uint8List _psk(int slot) =>
|
||||
Channel.parsePskHex(ReviewScript.channels[slot].pskHex);
|
||||
|
||||
String _id(Uint8List psk) => Channel.storageIdForPsk(psk)!;
|
||||
|
||||
String _messagesKey(String channelId) =>
|
||||
'channel_messages_${_scope}_$channelId';
|
||||
|
||||
List<String> _storedTexts(String channelId) {
|
||||
final raw = PrefsManager.instance.getString(_messagesKey(channelId));
|
||||
if (raw == null) return [];
|
||||
return [
|
||||
for (final entry in jsonDecode(raw) as List<dynamic>)
|
||||
(entry as Map<String, dynamic>)['text'] as String,
|
||||
];
|
||||
}
|
||||
|
||||
// SharedPreferences updates its in-memory cache synchronously.
|
||||
void _seedMessages(String channelId, List<String> texts) =>
|
||||
PrefsManager.instance.setString(
|
||||
_messagesKey(channelId),
|
||||
jsonEncode([
|
||||
for (var i = 0; i < texts.length; i++)
|
||||
{
|
||||
'senderName': 'Ghost',
|
||||
'text': texts[i],
|
||||
'timestamp': 1000 * (i + 1),
|
||||
'isOutgoing': false,
|
||||
'status': ChannelMessageStatus.sent.index,
|
||||
'messageId': 'seed-$channelId-$i',
|
||||
'plainText': true,
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
void _seedSlotMap(Map<int, String> slotIds) => PrefsManager.instance.setString(
|
||||
'channel_slot_ids_$_scope',
|
||||
jsonEncode({for (final e in slotIds.entries) '${e.key}': e.value}),
|
||||
);
|
||||
|
||||
/// Review radio that records every frame the app sends and can swallow some.
|
||||
class _TestRadio extends ReviewRadio {
|
||||
_TestRadio({this.swallow, this.afterHandle})
|
||||
: super(
|
||||
scheduledMessageInterval: const Duration(hours: 1),
|
||||
ackDelay: const Duration(milliseconds: 50),
|
||||
replyDelay: const Duration(hours: 1),
|
||||
);
|
||||
|
||||
final bool Function(Uint8List frame)? swallow;
|
||||
final void Function(_TestRadio radio, Uint8List frame)? afterHandle;
|
||||
final List<Uint8List> sent = [];
|
||||
|
||||
@override
|
||||
void handle(Uint8List frame) {
|
||||
sent.add(Uint8List.fromList(frame));
|
||||
if (swallow?.call(frame) ?? false) return;
|
||||
super.handle(frame);
|
||||
afterHandle?.call(this, frame);
|
||||
}
|
||||
|
||||
void deliver(Uint8List frame) => super.handle(frame);
|
||||
|
||||
List<int> codes() => [for (final f in sent) f.isEmpty ? -1 : f[0]];
|
||||
}
|
||||
|
||||
late MeshCoreConnector _connector;
|
||||
|
||||
/// Connects a fresh review radio. [seed] runs after review mode has cleared
|
||||
/// its storage and before SELF_INFO, standing in for a previous session.
|
||||
Future<void> _connect(_TestRadio radio, {void Function()? seed}) async {
|
||||
_connector.reviewRadioFactoryForTest = () {
|
||||
// beginReviewModeSession wipes the review scope before this runs.
|
||||
seed?.call();
|
||||
return radio;
|
||||
};
|
||||
await _connector.connectReview();
|
||||
addTearDown(_connector.disconnect);
|
||||
await _waitFor(() => _connector.channelMapConfirmed);
|
||||
}
|
||||
|
||||
Channel _channelAt(int slot) =>
|
||||
_connector.channels.firstWhere((c) => c.index == slot);
|
||||
|
||||
List<String> _texts(int slot) =>
|
||||
_connector.getChannelMessages(_channelAt(slot)).map((m) => m.text).toList();
|
||||
|
||||
Uint8List _logRxGroupText(Uint8List psk, String text, int timestampSecs) {
|
||||
final plain = BytesBuilder()
|
||||
..add(
|
||||
Uint8List(4)
|
||||
..buffer.asByteData().setUint32(0, timestampSecs, Endian.little),
|
||||
)
|
||||
..addByte(0)
|
||||
..add(utf8.encode(text))
|
||||
..addByte(0);
|
||||
final padded = Uint8List(((plain.length + 15) ~/ 16) * 16)
|
||||
..setRange(0, plain.length, plain.toBytes());
|
||||
final cipher = ECBBlockCipher(AESEngine())..init(true, KeyParameter(psk));
|
||||
final encrypted = Uint8List(padded.length);
|
||||
for (var i = 0; i < padded.length; i += 16) {
|
||||
cipher.processBlock(padded, i, encrypted, i);
|
||||
}
|
||||
final key32 = Uint8List(32)..setRange(0, 16, psk);
|
||||
final mac = crypto.Hmac(crypto.sha256, key32).convert(encrypted).bytes;
|
||||
final channelHash = crypto.sha256.convert(psk).bytes[0];
|
||||
return Uint8List.fromList([
|
||||
pushCodeLogRxData,
|
||||
40, // snr
|
||||
0xA0, // rssi
|
||||
0x15, // flood route, GRP_TXT payload
|
||||
0x00, // no path
|
||||
channelHash,
|
||||
mac[0],
|
||||
mac[1],
|
||||
...encrypted,
|
||||
]);
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUpAll(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
_connector = MeshCoreConnector();
|
||||
final retryService = MessageRetryService();
|
||||
_connector.initialize(
|
||||
retryService: retryService,
|
||||
pathHistoryService: PathHistoryService(StorageService()),
|
||||
);
|
||||
addTearDown(() {
|
||||
_connector.dispose();
|
||||
retryService.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
tearDown(() => _connector.channelSyncTimeoutMs = 2000);
|
||||
|
||||
final hikingId = _id(_psk(1));
|
||||
final ghostPsk = Uint8List.fromList(List<int>.generate(16, (i) => 200 - i));
|
||||
final ghostId = _id(ghostPsk);
|
||||
|
||||
test('a slot reused by another channel while away starts clean', () async {
|
||||
await _connect(
|
||||
_TestRadio(),
|
||||
seed: () {
|
||||
// Last session slot 1 held the ghost channel.
|
||||
_seedSlotMap({0: _id(_psk(0)), 1: ghostId, 2: _id(_psk(2))});
|
||||
_seedMessages(ghostId, ['ghost message']);
|
||||
},
|
||||
);
|
||||
await _waitFor(() => _texts(1).contains(_queuedHikingText));
|
||||
|
||||
expect(_channelAt(1).name, 'Hiking Group');
|
||||
expect(_texts(1), isNot(contains('ghost message')));
|
||||
// The old channel's history is kept under its own ID.
|
||||
expect(_storedTexts(ghostId), ['ghost message']);
|
||||
expect(_storedTexts(hikingId), contains(_queuedHikingText));
|
||||
expect(_connector.channelIdForSlot(1), hikingId);
|
||||
expect(
|
||||
jsonDecode(PrefsManager.instance.getString('channel_slot_ids_$_scope')!),
|
||||
containsPair('1', hikingId),
|
||||
);
|
||||
});
|
||||
|
||||
test('a PSK edit in place starts clean, and re-adding the old PSK in '
|
||||
'another slot brings its history back', () async {
|
||||
await _connect(_TestRadio());
|
||||
await _waitFor(() => _texts(1).contains(_queuedHikingText));
|
||||
await _connector.setChannelSmazEnabled(1, true);
|
||||
|
||||
await _connector.setChannel(1, 'Hiking Group', ghostPsk);
|
||||
expect(_connector.channelIdForSlot(1), ghostId);
|
||||
expect(_texts(1), isEmpty);
|
||||
expect(_connector.isChannelSmazEnabled(1), isFalse);
|
||||
expect(_storedTexts(hikingId), contains(_queuedHikingText));
|
||||
|
||||
await _connector.setChannel(6, 'Hiking Group', _psk(1));
|
||||
expect(_connector.channelIdForSlot(6), hikingId);
|
||||
expect(_texts(6), contains(_queuedHikingText));
|
||||
expect(_connector.isChannelSmazEnabled(6), isTrue);
|
||||
|
||||
// Restored history belongs to slot 6 now, so deleting from it works.
|
||||
final restored = _connector
|
||||
.getChannelMessages(_channelAt(6))
|
||||
.firstWhere((m) => m.text == _queuedHikingText);
|
||||
expect(restored.channelIndex, 6);
|
||||
await _connector.deleteChannelMessage(restored);
|
||||
expect(_texts(6), isNot(contains(_queuedHikingText)));
|
||||
expect(_storedTexts(hikingId), isNot(contains(_queuedHikingText)));
|
||||
});
|
||||
|
||||
test(
|
||||
'a PSK edit in place keeps the channel\'s place in the custom order',
|
||||
() async {
|
||||
await _connect(_TestRadio());
|
||||
await _connector.setChannelOrder([1, 0, 2]);
|
||||
expect(_connector.channels.first.index, 1);
|
||||
|
||||
await _connector.setChannel(1, 'Hiking Group', ghostPsk);
|
||||
expect(_connector.channels.first.index, 1);
|
||||
},
|
||||
);
|
||||
|
||||
test('deleting a channel clears its stored history', () async {
|
||||
await _connect(_TestRadio());
|
||||
await _waitFor(() => _texts(1).contains(_queuedHikingText));
|
||||
expect(_storedTexts(hikingId), isNotEmpty);
|
||||
|
||||
await _connector.deleteChannel(1);
|
||||
expect(_storedTexts(hikingId), isEmpty);
|
||||
});
|
||||
|
||||
test('MSG_WAITING before the channel sync waits for the slot map', () async {
|
||||
// DEVICE_INFO is held back so MSG_WAITING lands between SELF_INFO and the
|
||||
// start of the channel sync.
|
||||
late final _TestRadio radio;
|
||||
var deviceInfoHeld = false;
|
||||
radio = _TestRadio(
|
||||
swallow: (frame) {
|
||||
if (frame[0] != cmdDeviceQuery || deviceInfoHeld) return false;
|
||||
deviceInfoHeld = true;
|
||||
Future<void>.delayed(
|
||||
const Duration(milliseconds: 400),
|
||||
() => radio.deliver(frame),
|
||||
);
|
||||
return true;
|
||||
},
|
||||
afterHandle: (radio, frame) {
|
||||
if (frame[0] == cmdAppStart) {
|
||||
radio.emitForTest(ReviewFrames.msgWaiting());
|
||||
}
|
||||
},
|
||||
);
|
||||
await _connect(radio);
|
||||
await _waitFor(() => _texts(1).contains(_queuedHikingText));
|
||||
|
||||
final codes = radio.codes();
|
||||
final firstSync = codes.indexOf(cmdSyncNextMessage);
|
||||
final lastGetChannel = codes.lastIndexOf(cmdGetChannel);
|
||||
expect(firstSync, isNonNegative);
|
||||
expect(lastGetChannel, isNonNegative);
|
||||
expect(firstSync, greaterThan(lastGetChannel));
|
||||
});
|
||||
|
||||
test('a slot that never answers retries the sync, then releases the '
|
||||
'queue with the saved map', () async {
|
||||
_connector.channelSyncTimeoutMs = 30;
|
||||
final radio = _TestRadio(
|
||||
swallow: (frame) => frame[0] == cmdGetChannel && frame[1] == 1,
|
||||
);
|
||||
await _connect(
|
||||
radio,
|
||||
seed: () => _seedSlotMap({0: _id(_psk(0)), 1: hikingId, 2: _id(_psk(2))}),
|
||||
);
|
||||
await _waitFor(() => _storedTexts(hikingId).contains(_queuedHikingText));
|
||||
|
||||
final firstSync = radio.codes().indexOf(cmdSyncNextMessage);
|
||||
final passes = radio.sent
|
||||
.take(firstSync)
|
||||
.where((f) => f[0] == cmdGetChannel && f[1] == 0)
|
||||
.length;
|
||||
expect(passes, 3);
|
||||
expect(_connector.channelIdForSlot(1), hikingId);
|
||||
});
|
||||
|
||||
test('two slots with the same PSK share one history', () async {
|
||||
final radio = _TestRadio();
|
||||
await _connect(
|
||||
radio,
|
||||
seed: () => radio.handle(buildSetChannelFrame(5, 'Hiking Twin', _psk(1))),
|
||||
);
|
||||
await _waitFor(() => _texts(1).contains(_queuedHikingText));
|
||||
expect(_connector.channelIdForSlot(5), hikingId);
|
||||
expect(_texts(5), _texts(1));
|
||||
|
||||
// Settings are stored per channel, so both slots see a change.
|
||||
await _connector.setChannelSmazEnabled(5, true);
|
||||
expect(_connector.isChannelSmazEnabled(1), isTrue);
|
||||
await _connector.setChannelRegion(1, 'test-region');
|
||||
expect(_connector.getChannelRegion(5), 'test-region');
|
||||
|
||||
radio.emitForTest(
|
||||
ReviewFrames.channelMessage(
|
||||
channelIndex: 5,
|
||||
sender: 'Sam',
|
||||
message: 'from the twin slot',
|
||||
timestampSecs: DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
||||
),
|
||||
);
|
||||
await _waitFor(() => _texts(1).contains('from the twin slot'));
|
||||
expect(_texts(5), contains('from the twin slot'));
|
||||
expect(
|
||||
_storedTexts(hikingId).where((t) => t == 'from the twin slot'),
|
||||
hasLength(1),
|
||||
);
|
||||
});
|
||||
|
||||
test('an RX-log message is filed by its PSK-derived channel ID', () async {
|
||||
final radio = _TestRadio();
|
||||
await _connect(radio);
|
||||
final localId = _id(_psk(2));
|
||||
radio.emitForTest(
|
||||
_logRxGroupText(
|
||||
_psk(2),
|
||||
'Ranger Pat: heard over the air',
|
||||
DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
||||
),
|
||||
);
|
||||
await _waitFor(() => _texts(2).contains('heard over the air'));
|
||||
expect(_storedTexts(localId), contains('heard over the air'));
|
||||
expect(_texts(1), isNot(contains('heard over the air')));
|
||||
});
|
||||
}
|
||||
@@ -330,6 +330,40 @@ void main() {
|
||||
);
|
||||
expect(r.pendingCount, 2);
|
||||
});
|
||||
|
||||
test('clearChannel stops a reused slot finishing with old bytes', () {
|
||||
final oldSet = buildImageChunks(
|
||||
payload: payloadOf(300, seed: 1),
|
||||
metadata: stdMeta,
|
||||
senderPrefix: senderA,
|
||||
imgId: 9,
|
||||
);
|
||||
final newPayload = payloadOf(300, seed: 2);
|
||||
final newSet = buildImageChunks(
|
||||
payload: newPayload,
|
||||
metadata: stdMeta,
|
||||
senderPrefix: senderA,
|
||||
imgId: 9,
|
||||
);
|
||||
expect(newSet.dataChunkCount, greaterThanOrEqualTo(2));
|
||||
final failures = <ImageReassemblyFailure>[];
|
||||
final r = ImageReassembler(onFailed: failures.add);
|
||||
r.addChunk(oldSet.blobs[0], channelIndex: 3);
|
||||
r.addChunk(oldSet.blobs[0], channelIndex: 4);
|
||||
|
||||
r.clearChannel(3);
|
||||
expect(failures.single.key.channelIndex, 3);
|
||||
expect(
|
||||
failures.single.reason,
|
||||
ImageReassemblyFailureReason.channelChanged,
|
||||
);
|
||||
expect(r.pendingKeys.single.channelIndex, 4);
|
||||
|
||||
// Without the clear, these would complete with the old chunk 0.
|
||||
final dataBlobs = newSet.blobs.sublist(0, newSet.dataChunkCount);
|
||||
expect(feed(r, dataBlobs.sublist(1), channelIndex: 3), isNull);
|
||||
expect(feed(r, [dataBlobs[0]], channelIndex: 3)!.data, newPayload);
|
||||
});
|
||||
});
|
||||
|
||||
group('parity recovery', () {
|
||||
|
||||
@@ -604,6 +604,7 @@ void main() {
|
||||
() async {
|
||||
final store = ChannelMessageStore()..publicKeyHex = '1234567890';
|
||||
final channelIndex = 1;
|
||||
const channelId = '0123456789abcdef';
|
||||
|
||||
final rawPath = Uint8List(64)
|
||||
..[0] = 0xBB
|
||||
@@ -623,11 +624,11 @@ void main() {
|
||||
|
||||
final prefs = PrefsManager.instance;
|
||||
await prefs.setString(
|
||||
'${store.keyFor}$channelIndex',
|
||||
'${store.keyFor}_$channelId',
|
||||
jsonEncode(messageJson),
|
||||
);
|
||||
|
||||
final messages = await store.loadChannelMessages(channelIndex);
|
||||
final messages = await store.loadChannelMessages(channelId);
|
||||
expect(messages, hasLength(1));
|
||||
expect(messages.first.pathLength, equals(1));
|
||||
expect(
|
||||
|
||||
@@ -36,6 +36,8 @@ ChannelMessage _ch(
|
||||
channelIndex: 0,
|
||||
);
|
||||
|
||||
const _channelId = '0123456789abcdef';
|
||||
|
||||
void main() {
|
||||
final base = DateTime(2026, 10, 1, 12);
|
||||
|
||||
@@ -127,10 +129,10 @@ void main() {
|
||||
await _init();
|
||||
final store = ChannelMessageStore()..setPublicKeyHex = _device;
|
||||
final received = base.add(const Duration(seconds: 42));
|
||||
await store.saveChannelMessages(0, [
|
||||
await store.saveChannelMessages(_channelId, [
|
||||
_ch('one', timestamp: base, receivedAt: received),
|
||||
]);
|
||||
final loaded = await store.loadChannelMessages(0);
|
||||
final loaded = await store.loadChannelMessages(_channelId);
|
||||
expect(loaded.single.receivedAt, received);
|
||||
expect(loaded.single.timestamp, base);
|
||||
});
|
||||
@@ -167,14 +169,14 @@ void main() {
|
||||
'plainText': true,
|
||||
};
|
||||
await _init({
|
||||
'channel_messages_${_device.substring(0, 10)}0': jsonEncode([
|
||||
'channel_messages_${_device.substring(0, 10)}_$_channelId': jsonEncode([
|
||||
record('old', past),
|
||||
record('ahead', future),
|
||||
]),
|
||||
});
|
||||
final store = ChannelMessageStore()..setPublicKeyHex = _device;
|
||||
final before = DateTime.now();
|
||||
final loaded = await store.loadChannelMessages(0);
|
||||
final loaded = await store.loadChannelMessages(_channelId);
|
||||
expect(loaded, hasLength(2));
|
||||
expect(
|
||||
loaded[0].receivedAt.millisecondsSinceEpoch,
|
||||
|
||||
@@ -210,6 +210,54 @@ void main() {
|
||||
expect(h.decoder.calls, 1);
|
||||
});
|
||||
|
||||
test('a stream started before its slot had an ID picks one up', () async {
|
||||
final h = _build();
|
||||
final set = buildImageChunks(
|
||||
payload: _payload(kImageChunkFirstCapacity + kImageChunkCapacity + 1),
|
||||
metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard),
|
||||
senderPrefix: kSender,
|
||||
imgId: 5,
|
||||
);
|
||||
expect(set.dataChunkCount, 3);
|
||||
|
||||
final first = await h.store.handleOutcome(
|
||||
h.reassembler.addChunk(set.blobs[0], channelIndex: 3),
|
||||
channelIndex: 3,
|
||||
);
|
||||
expect(first!.channelId, isNull);
|
||||
// A second data chunk of three neither completes nor recovers it.
|
||||
final second = await h.store.handleOutcome(
|
||||
h.reassembler.addChunk(set.blobs[1], channelIndex: 3),
|
||||
channelIndex: 3,
|
||||
channelId: 'chan-id',
|
||||
);
|
||||
expect(second!.state, ReceivedImageState.receiving);
|
||||
expect(second.streamId, first.streamId);
|
||||
expect(second.channelId, 'chan-id');
|
||||
});
|
||||
|
||||
test('a stream completed after its slot got an ID keeps it', () async {
|
||||
final h = _build();
|
||||
final set = buildImageChunks(
|
||||
payload: _payload(kImageChunkFirstCapacity + 1),
|
||||
metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard),
|
||||
senderPrefix: kSender,
|
||||
imgId: 6,
|
||||
);
|
||||
final first = await h.store.handleOutcome(
|
||||
h.reassembler.addChunk(set.blobs[0], channelIndex: 3),
|
||||
channelIndex: 3,
|
||||
);
|
||||
expect(first!.channelId, isNull);
|
||||
final done = await h.store.handleOutcome(
|
||||
h.reassembler.addChunk(set.blobs[1], channelIndex: 3),
|
||||
channelIndex: 3,
|
||||
channelId: 'chan-id',
|
||||
);
|
||||
expect(done!.streamId, first.streamId);
|
||||
expect(done.channelId, 'chan-id');
|
||||
});
|
||||
|
||||
test('two-chunk image reports 1 of 2 while incomplete', () async {
|
||||
final h = _build();
|
||||
final set = buildImageChunks(
|
||||
@@ -962,7 +1010,7 @@ void main() {
|
||||
|
||||
group('deletion hooks', () {
|
||||
test(
|
||||
'deleteImagesForChannel reclaims every image of one conversation',
|
||||
'deleteImagesForChannelId reclaims every image of one conversation',
|
||||
() async {
|
||||
final h = _build();
|
||||
final a = await _completeOne(h, imgId: 130);
|
||||
@@ -972,6 +1020,7 @@ void main() {
|
||||
// A third image on another channel must survive.
|
||||
final other = await h.store.registerOutgoing(
|
||||
channelIndex: 9,
|
||||
channelId: 'fedcba9876543210',
|
||||
senderPrefix: kSelf,
|
||||
imgId: 5,
|
||||
previewPng: Uint8List.fromList(List<int>.filled(32, 2)),
|
||||
@@ -979,7 +1028,7 @@ void main() {
|
||||
chunkCount: 1,
|
||||
);
|
||||
|
||||
final removed = await h.store.deleteImagesForChannel(3);
|
||||
final removed = await h.store.deleteImagesForChannelId(_channel3Id);
|
||||
expect(removed, containsAll(<String>[a.streamId, b.streamId]));
|
||||
expect(h.store.entryFor(a.streamId), isNull);
|
||||
expect(h.store.entryFor(b.streamId), isNull);
|
||||
@@ -1480,7 +1529,10 @@ Future<ReceivedImageEntry> _completeOne(
|
||||
final entry = await h.store.handleOutcome(
|
||||
h.reassembler.addChunk(set.blobs[0], channelIndex: 3, now: h.clock()),
|
||||
channelIndex: 3,
|
||||
channelId: _channel3Id,
|
||||
at: h.clock(),
|
||||
);
|
||||
return entry!;
|
||||
}
|
||||
|
||||
const _channel3Id = '0123456789abcdef';
|
||||
@@ -0,0 +1,351 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/channel.dart';
|
||||
import 'package:meshcore_open/models/channel_message.dart';
|
||||
import 'package:meshcore_open/models/image_codec_support.dart';
|
||||
import 'package:meshcore_open/services/received_image_store.dart';
|
||||
import 'package:meshcore_open/storage/channel_message_store.dart';
|
||||
import 'package:meshcore_open/storage/channel_order_store.dart';
|
||||
import 'package:meshcore_open/storage/channel_region_store.dart';
|
||||
import 'package:meshcore_open/storage/channel_settings_store.dart';
|
||||
import 'package:meshcore_open/storage/channel_storage_migration.dart';
|
||||
import 'package:meshcore_open/storage/channel_store.dart';
|
||||
import 'package:meshcore_open/storage/legacy_key_migration.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
const _deviceA = 'aaaaaaaaaa0123456789';
|
||||
const _deviceB = 'bbbbbbbbbb0123456789';
|
||||
const _scopeA = 'aaaaaaaaaa';
|
||||
|
||||
final _pskOne = Uint8List.fromList(List<int>.generate(16, (i) => i + 1));
|
||||
final _pskTwo = Uint8List.fromList(List<int>.generate(16, (i) => 100 + i));
|
||||
final _idOne = Channel.storageIdForPsk(_pskOne)!;
|
||||
final _idTwo = Channel.storageIdForPsk(_pskTwo)!;
|
||||
|
||||
Future<void> _init([Map<String, Object> values = const {}]) async {
|
||||
SharedPreferences.setMockInitialValues(values);
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
ChannelMessageStore().forgetArchive();
|
||||
}
|
||||
|
||||
ChannelMessage _ch(String text, int i) => ChannelMessage(
|
||||
senderKey: null,
|
||||
senderName: 'Bob',
|
||||
text: text,
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(1000 * i),
|
||||
isOutgoing: false,
|
||||
status: ChannelMessageStatus.sent,
|
||||
channelIndex: 0,
|
||||
messageId: '$text-$i',
|
||||
);
|
||||
|
||||
String _storedMessages(List<String> texts) => jsonEncode([
|
||||
for (var i = 0; i < texts.length; i++)
|
||||
{
|
||||
'senderName': 'Bob',
|
||||
'text': texts[i],
|
||||
'timestamp': 1000 * (i + 1),
|
||||
'isOutgoing': false,
|
||||
'status': ChannelMessageStatus.sent.index,
|
||||
'messageId': '${texts[i]}-$i',
|
||||
'plainText': true,
|
||||
},
|
||||
]);
|
||||
|
||||
String _cachedChannels(Map<int, Uint8List> slots) => jsonEncode([
|
||||
for (final entry in slots.entries)
|
||||
{
|
||||
'index': entry.key,
|
||||
'name': 'ch${entry.key}',
|
||||
'psk': base64Encode(entry.value),
|
||||
'unreadCount': 0,
|
||||
},
|
||||
]);
|
||||
|
||||
void main() {
|
||||
tearDown(scopesWithoutLegacyMigration.clear);
|
||||
|
||||
group('channel ID', () {
|
||||
test('is stable, 16 hex chars, and absent for an empty slot', () {
|
||||
expect(_idOne, hasLength(16));
|
||||
expect(_idOne, matches(RegExp(r'^[0-9a-f]{16}$')));
|
||||
expect(Channel.storageIdForPsk(Uint8List.fromList(_pskOne)), _idOne);
|
||||
expect(_idOne, isNot(_idTwo));
|
||||
expect(Channel.storageIdForPsk(Uint8List(16)), isNull);
|
||||
expect(Channel.empty(3).storageId, isNull);
|
||||
expect(Channel(index: 5, name: 'x', psk: _pskOne).storageId, _idOne);
|
||||
});
|
||||
});
|
||||
|
||||
group('ID-keyed stores', () {
|
||||
test('messages save, load and clear by channel ID', () async {
|
||||
await _init();
|
||||
final store = ChannelMessageStore()..setPublicKeyHex = _deviceA;
|
||||
await store.saveChannelMessages(_idOne, [_ch('one', 1)]);
|
||||
await store.saveChannelMessages(_idTwo, [_ch('two', 1)]);
|
||||
|
||||
expect((await store.loadChannelMessages(_idOne)).single.text, 'one');
|
||||
expect((await store.loadChannelMessages(_idTwo)).single.text, 'two');
|
||||
expect(
|
||||
PrefsManager.instance.containsKey(
|
||||
'channel_messages_${_scopeA}_$_idOne',
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
|
||||
await store.clearChannelMessages(_idOne);
|
||||
expect(await store.loadChannelMessages(_idOne), isEmpty);
|
||||
expect(await store.loadChannelMessages(_idTwo), hasLength(1));
|
||||
});
|
||||
|
||||
test('the same channel ID is isolated per radio scope', () async {
|
||||
await _init();
|
||||
final a = ChannelMessageStore()..setPublicKeyHex = _deviceA;
|
||||
final b = ChannelMessageStore()..setPublicKeyHex = _deviceB;
|
||||
await a.saveChannelMessages(_idOne, [_ch('a', 1)]);
|
||||
|
||||
expect(await b.loadChannelMessages(_idOne), isEmpty);
|
||||
final settingsB = ChannelSettingsStore()..setPublicKeyHex = _deviceB;
|
||||
final settingsA = ChannelSettingsStore()..setPublicKeyHex = _deviceA;
|
||||
await settingsA.saveSmazEnabled(_idOne, true);
|
||||
expect(await settingsA.loadSmazEnabled(_idOne), isTrue);
|
||||
expect(await settingsB.loadSmazEnabled(_idOne), isFalse);
|
||||
});
|
||||
|
||||
test('the archive follows the channel ID', () async {
|
||||
await _init();
|
||||
final store = ChannelMessageStore()..setPublicKeyHex = _deviceA;
|
||||
store.setArchived(_idOne, [_ch('old', 1), _ch('older', 2)]);
|
||||
expect(store.archivedCount(_idOne), 2);
|
||||
expect(store.archivedCount(_idTwo), isNull);
|
||||
|
||||
await store.saveChannelMessages(_idOne, [_ch('new', 3)]);
|
||||
expect((await store.loadChannelMessages(_idOne)).map((m) => m.text), [
|
||||
'old',
|
||||
'older',
|
||||
'new',
|
||||
]);
|
||||
store.forgetArchive(_idOne);
|
||||
expect(store.archivedCount(_idOne), isNull);
|
||||
});
|
||||
|
||||
test('settings, region and order are keyed by channel ID', () async {
|
||||
await _init();
|
||||
final settings = ChannelSettingsStore()..setPublicKeyHex = _deviceA;
|
||||
await settings.saveCyr2LatEnabled(_idOne, true);
|
||||
await settings.saveUrlImagesEnabled(_idOne, true);
|
||||
await settings.saveCyr2LatProfileId(_idOne, 'sr');
|
||||
expect(await settings.loadCyr2LatEnabled(_idOne), isTrue);
|
||||
expect(await settings.loadUrlImagesEnabled(_idOne), isTrue);
|
||||
expect(await settings.loadCyr2LatProfileId(_idOne), 'sr');
|
||||
expect(await settings.loadCyr2LatEnabled(_idTwo), isFalse);
|
||||
await settings.clearChannel(_idOne);
|
||||
expect(await settings.loadCyr2LatEnabled(_idOne), isFalse);
|
||||
expect(await settings.loadCyr2LatProfileId(_idOne), isNull);
|
||||
|
||||
final region = ChannelRegionStore()..setPublicKeyHex = _deviceA;
|
||||
await region.saveRegion(_idOne, 'EU');
|
||||
expect(await region.loadRegion(_idOne), 'EU');
|
||||
expect(await region.loadRegion(_idTwo), '');
|
||||
await ChannelRegionStore.clearRegionEverywhere('EU');
|
||||
expect(await region.loadRegion(_idOne), '');
|
||||
|
||||
final order = ChannelOrderStore()..setPublicKeyHex = _deviceA;
|
||||
await order.saveChannelOrder([_idTwo, _idOne]);
|
||||
expect(await order.loadChannelOrder(), [_idTwo, _idOne]);
|
||||
});
|
||||
});
|
||||
|
||||
group('migration', () {
|
||||
Map<String, Object> legacyValues() => {
|
||||
'channels$_scopeA': _cachedChannels({0: _pskOne, 2: _pskTwo}),
|
||||
'channel_messages_${_scopeA}0': _storedMessages(['hello']),
|
||||
'channel_messages_2': _storedMessages(['unscoped']),
|
||||
'channel_messages_${_scopeA}5': _storedMessages(['orphan']),
|
||||
'channel_smaz_${_scopeA}0': true,
|
||||
'channel_cyr2lat_${_scopeA}2': true,
|
||||
'channel_url_images_${_scopeA}2': true,
|
||||
'channel_cyr2lat_${_scopeA}profile_2': 'sr',
|
||||
'channel_region_${_scopeA}0': 'EU',
|
||||
'channel_order_$_scopeA': jsonEncode([2, 5, 0]),
|
||||
};
|
||||
|
||||
test('moves messages, settings, region and order to channel IDs', () async {
|
||||
await _init(legacyValues());
|
||||
final mapping = await ChannelStorageMigration.migrate(_scopeA);
|
||||
expect(mapping, {0: _idOne, 2: _idTwo});
|
||||
|
||||
final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA;
|
||||
expect((await messages.loadChannelMessages(_idOne)).single.text, 'hello');
|
||||
// The unscoped legacy key migrates too.
|
||||
expect(
|
||||
(await messages.loadChannelMessages(_idTwo)).single.text,
|
||||
'unscoped',
|
||||
);
|
||||
|
||||
final settings = ChannelSettingsStore()..setPublicKeyHex = _deviceA;
|
||||
expect(await settings.loadSmazEnabled(_idOne), isTrue);
|
||||
expect(await settings.loadSmazEnabled(_idTwo), isFalse);
|
||||
expect(await settings.loadCyr2LatEnabled(_idTwo), isTrue);
|
||||
expect(await settings.loadUrlImagesEnabled(_idTwo), isTrue);
|
||||
expect(await settings.loadCyr2LatProfileId(_idTwo), 'sr');
|
||||
|
||||
final region = ChannelRegionStore()..setPublicKeyHex = _deviceA;
|
||||
expect(await region.loadRegion(_idOne), 'EU');
|
||||
|
||||
final order = ChannelOrderStore()..setPublicKeyHex = _deviceA;
|
||||
expect(await order.loadChannelOrder(), [_idTwo, _idOne]);
|
||||
|
||||
final prefs = PrefsManager.instance;
|
||||
expect(prefs.containsKey('channel_messages_${_scopeA}0'), isFalse);
|
||||
expect(prefs.containsKey('channel_messages_2'), isFalse);
|
||||
expect(prefs.containsKey('channel_smaz_${_scopeA}0'), isFalse);
|
||||
expect(prefs.containsKey('channel_region_${_scopeA}0'), isFalse);
|
||||
// A slot with no cached PSK is left alone.
|
||||
expect(prefs.containsKey('channel_messages_${_scopeA}5'), isTrue);
|
||||
// The slot map is seeded for the first post-migration diff.
|
||||
expect(
|
||||
await (ChannelStore()..setPublicKeyHex = _scopeA).loadSlotChannelIds(),
|
||||
{0: _idOne, 2: _idTwo},
|
||||
);
|
||||
});
|
||||
|
||||
test('runs once per radio', () async {
|
||||
await _init(legacyValues());
|
||||
await ChannelStorageMigration.migrate(_scopeA);
|
||||
await PrefsManager.instance.setString(
|
||||
'channel_messages_${_scopeA}0',
|
||||
_storedMessages(['late']),
|
||||
);
|
||||
expect(await ChannelStorageMigration.migrate(_scopeA), isEmpty);
|
||||
final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA;
|
||||
expect((await messages.loadChannelMessages(_idOne)).single.text, 'hello');
|
||||
expect(
|
||||
PrefsManager.instance.containsKey('channel_messages_${_scopeA}0'),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
test('a rerun after an interrupted migration loses and duplicates '
|
||||
'nothing', () async {
|
||||
// Killed after the new keys were written but before the old ones
|
||||
// were removed and the done flag set.
|
||||
await _init({
|
||||
'channels$_scopeA': _cachedChannels({0: _pskOne, 2: _pskTwo}),
|
||||
'channel_messages_${_scopeA}0': _storedMessages(['hello']),
|
||||
'channel_messages_${_scopeA}_$_idOne': _storedMessages(['hello']),
|
||||
'channel_order_$_scopeA': jsonEncode([_idTwo, _idOne]),
|
||||
});
|
||||
await ChannelStorageMigration.migrate(_scopeA);
|
||||
|
||||
final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA;
|
||||
expect((await messages.loadChannelMessages(_idOne)).map((m) => m.text), [
|
||||
'hello',
|
||||
]);
|
||||
final order = ChannelOrderStore()..setPublicKeyHex = _deviceA;
|
||||
expect(await order.loadChannelOrder(), [_idTwo, _idOne]);
|
||||
expect(
|
||||
PrefsManager.instance.containsKey('channel_messages_${_scopeA}0'),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
|
||||
test('skips a scope that must not adopt legacy data', () async {
|
||||
await _init(legacyValues());
|
||||
scopesWithoutLegacyMigration.add(_scopeA);
|
||||
expect(await ChannelStorageMigration.migrate(_scopeA), isEmpty);
|
||||
final prefs = PrefsManager.instance;
|
||||
expect(prefs.containsKey('channel_messages_${_scopeA}0'), isTrue);
|
||||
expect(prefs.containsKey('channel_storage_v2_$_scopeA'), isFalse);
|
||||
expect(prefs.containsKey('channel_messages_2'), isTrue);
|
||||
});
|
||||
|
||||
test('two slots with the same PSK merge into one history', () async {
|
||||
await _init({
|
||||
'channels$_scopeA': _cachedChannels({1: _pskOne, 4: _pskOne}),
|
||||
'channel_messages_${_scopeA}1': _storedMessages(['first']),
|
||||
'channel_messages_${_scopeA}4': _storedMessages(['second', 'third']),
|
||||
});
|
||||
expect(await ChannelStorageMigration.migrate(_scopeA), {
|
||||
1: _idOne,
|
||||
4: _idOne,
|
||||
});
|
||||
final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA;
|
||||
expect(
|
||||
(await messages.loadChannelMessages(_idOne)).map((m) => m.text),
|
||||
unorderedEquals(['first', 'second', 'third']),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('received images', () {
|
||||
final png = Uint8List.fromList(List<int>.filled(32, 7));
|
||||
|
||||
Future<ReceivedImageEntry> outgoing(
|
||||
ReceivedImageStore store, {
|
||||
required int slot,
|
||||
String? channelId,
|
||||
int imgId = 1,
|
||||
}) => store.registerOutgoing(
|
||||
channelIndex: slot,
|
||||
channelId: channelId,
|
||||
senderPrefix: 0x1234,
|
||||
imgId: imgId,
|
||||
previewPng: png,
|
||||
rate: AeicRatePoint.ft32,
|
||||
chunkCount: 1,
|
||||
);
|
||||
|
||||
test('an entry round-trips its channel ID', () async {
|
||||
final store = ReceivedImageStore(decoder: null);
|
||||
final entry = await outgoing(store, slot: 2, channelId: _idOne);
|
||||
final json = entry.toJson();
|
||||
expect(json['channelId'], _idOne);
|
||||
expect(ReceivedImageEntry.fromJson(json).channelId, _idOne);
|
||||
expect(ReceivedImageEntry.fromJson({'streamId': 'x'}).channelId, isNull);
|
||||
});
|
||||
|
||||
test('legacy entries get the ID their slot held', () async {
|
||||
final blobs = InMemoryReceivedImageBlobStore();
|
||||
final first = ReceivedImageStore(blobs: blobs, decoder: null);
|
||||
final onSlot2 = await outgoing(first, slot: 2, imgId: 1);
|
||||
final onSlot6 = await outgoing(first, slot: 6, imgId: 2);
|
||||
final stamped = await outgoing(first, slot: 2, imgId: 3, channelId: 'x');
|
||||
|
||||
final store = ReceivedImageStore(blobs: blobs, decoder: null);
|
||||
await store.load();
|
||||
await store.stampLegacyChannelIds({2: _idOne, 3: _idTwo});
|
||||
|
||||
expect(store.entryFor(onSlot2.streamId)!.channelId, _idOne);
|
||||
expect(store.entryFor(onSlot6.streamId)!.channelId, isNull);
|
||||
expect(store.entryFor(stamped.streamId)!.channelId, 'x');
|
||||
// Persisted, so the next launch keeps the stamp.
|
||||
final reloaded = ReceivedImageStore(blobs: blobs, decoder: null);
|
||||
await reloaded.load();
|
||||
expect(reloaded.entryFor(onSlot2.streamId)!.channelId, _idOne);
|
||||
});
|
||||
|
||||
test('delete by channel ID leaves a reused slot alone', () async {
|
||||
final store = ReceivedImageStore(decoder: null);
|
||||
final old = await outgoing(store, slot: 1, channelId: _idOne, imgId: 1);
|
||||
final reused = await outgoing(
|
||||
store,
|
||||
slot: 1,
|
||||
channelId: _idTwo,
|
||||
imgId: 2,
|
||||
);
|
||||
|
||||
expect(store.entriesForChannel(_idTwo).map((e) => e.streamId), [
|
||||
reused.streamId,
|
||||
]);
|
||||
final removed = await store.deleteImagesForChannelId(_idOne);
|
||||
expect(removed, [old.streamId]);
|
||||
expect(store.entryFor(old.streamId), isNull);
|
||||
expect(store.entryFor(reused.streamId), isNotNull);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -43,6 +43,8 @@ ChannelMessage _ch(int i) => ChannelMessage(
|
||||
|
||||
MessageStore _messageStore() => MessageStore()..setPublicKeyHex = _device;
|
||||
|
||||
const _channelId = '0123456789abcdef';
|
||||
|
||||
void main() {
|
||||
group('MessageStore window persistence', () {
|
||||
test('saving the window keeps archived history ahead of it', () async {
|
||||
@@ -179,27 +181,30 @@ void main() {
|
||||
await _init();
|
||||
final store = ChannelMessageStore()..setPublicKeyHex = _device;
|
||||
final all = [for (var i = 0; i < 8; i++) _ch(i)];
|
||||
await store.saveChannelMessages(0, all);
|
||||
await store.saveChannelMessages(_channelId, all);
|
||||
|
||||
final loaded = await store.loadChannelMessages(0);
|
||||
store.setArchived(0, loaded.sublist(0, 5));
|
||||
await store.saveChannelMessages(0, [...loaded.sublist(5), _ch(8)]);
|
||||
final loaded = await store.loadChannelMessages(_channelId);
|
||||
store.setArchived(_channelId, loaded.sublist(0, 5));
|
||||
await store.saveChannelMessages(_channelId, [
|
||||
...loaded.sublist(5),
|
||||
_ch(8),
|
||||
]);
|
||||
|
||||
final reloaded = await store.loadChannelMessages(0);
|
||||
final reloaded = await store.loadChannelMessages(_channelId);
|
||||
expect(reloaded.map((m) => m.text), [for (var i = 0; i <= 8; i++) 'c$i']);
|
||||
});
|
||||
|
||||
test('clearing through another instance resets the archive', () async {
|
||||
await _init();
|
||||
final store = ChannelMessageStore()..setPublicKeyHex = _device;
|
||||
store.setArchived(0, [_ch(0), _ch(1)]);
|
||||
await store.saveChannelMessages(0, [_ch(2)]);
|
||||
store.setArchived(_channelId, [_ch(0), _ch(1)]);
|
||||
await store.saveChannelMessages(_channelId, [_ch(2)]);
|
||||
|
||||
await (ChannelMessageStore()..setPublicKeyHex = _device)
|
||||
.clearChannelMessages(0);
|
||||
await store.saveChannelMessages(0, [_ch(3)]);
|
||||
.clearChannelMessages(_channelId);
|
||||
await store.saveChannelMessages(_channelId, [_ch(3)]);
|
||||
|
||||
final reloaded = await store.loadChannelMessages(0);
|
||||
final reloaded = await store.loadChannelMessages(_channelId);
|
||||
expect(reloaded.map((m) => m.text), ['c3']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,6 +17,8 @@ Future<void> _init(Map<String, Object> values) async {
|
||||
await PrefsManager.initialize();
|
||||
}
|
||||
|
||||
const _channelId = '0123456789abcdef';
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'message store skips a malformed record instead of dropping all',
|
||||
@@ -42,13 +44,13 @@ void main() {
|
||||
|
||||
test('channel message store skips a malformed record', () async {
|
||||
await _init({
|
||||
'channel_messages_${_device.substring(0, 10)}0': jsonEncode([
|
||||
'channel_messages_${_device.substring(0, 10)}_$_channelId': jsonEncode([
|
||||
{'text': 'hi', 'timestamp': 1000, 'status': 1},
|
||||
'garbage',
|
||||
]),
|
||||
});
|
||||
final store = ChannelMessageStore()..setPublicKeyHex = _device;
|
||||
final messages = await store.loadChannelMessages(0);
|
||||
final messages = await store.loadChannelMessages(_channelId);
|
||||
expect(messages.map((m) => m.text), ['hi']);
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user