Files
meshcore-open/lib/storage/unread_store.dart
T
zjs81 25f197c979 Fix review findings, add default flood scope, and address recent issues
Review fixes:
- Keep stored message history beyond the 200-message window; stop
  messages leaking between radios; reset link/session state on disconnect
- Accept firmware's 176-byte RX frames over USB/TCP
- Hold APP_START during contact sync; contact-sync watchdog; replay DMs
  from not-yet-known senders; tombstone late command replies; finish
  channel sync on ERR_NOT_FOUND; fail region-scoped sends cleanly
- DM retry watchdog when RESP_CODE_SENT never arrives; late repeater CLI
  replies; ACK hash collisions; UTF-8-safe name truncation
- Image pipeline: delete-during-decode, lifecycle cancels, decoder memory
  release, entry cap, dead worker recovery, atomic model writes
- Storage: deterministic reaction hash across web/native, Smaz
  double-decode, per-entry parsing, per-radio path history and regions,
  review-mode data isolation
- UI: safe channel slot selection, byte-length name limits, double-send
  guard, mounted checks, localized hardcoded strings
- Skip persisted-store reload on repeat SELF_INFO

Features:
- Radio default flood scope (firmware ver 11+) and explicit unscoped
  sends (ver 12+)
- Scan for nearby nodes (#570)
- Optional distinct first-hop repeater counting for channel resend (#589)
- Optional region next to hop count (#580)

Issues:
- Message text follows system font size (#569)
- Repeater/room password field accepts 20 chars (#576)
- TCP auto-reconnect and keepalive (#571)
- Order feeds by local receive time; flag future timestamps (#584)
- Coding rate help text (#568), French "Favoris" (#575)
- iOS/macOS app badge now clears

Translations for all new strings in every locale.
2026-10-11 01:25:31 -07:00

106 lines
3.2 KiB
Dart

import 'dart:async';
import 'dart:convert';
import '../utils/app_logger.dart';
import 'legacy_key_migration.dart';
import 'prefs_manager.dart';
/// Storage for unread message tracking with debounced writes to reduce I/O.
class UnreadStore {
static const String _keyPrefix = 'contact_unread_count';
String publicKeyHex = '';
set setPublicKeyHex(String value) =>
publicKeyHex = value.length >= 10 ? value.substring(0, 10) : '';
String get keyFor => '$_keyPrefix$publicKeyHex';
// Debounce timers to batch rapid writes
Timer? _contactUnreadSaveTimer;
static const Duration _saveDebounceDuration = Duration(milliseconds: 500);
// Pending write data
Map<String, int>? _pendingContactUnreadCount;
/// Dispose timers when no longer needed
void dispose() {
_contactUnreadSaveTimer?.cancel();
}
Future<Map<String, int>> loadContactUnreadCount() async {
if (publicKeyHex.isEmpty) {
appLogger.warn('Public key hex is not set. Cannot load unread counts.');
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 messages from legacy key $_keyPrefix to scoped key $keyFor',
);
await prefs.setString(keyFor, legacyJsonString);
jsonString = legacyJsonString;
}
}
if (jsonString == null || jsonString.isEmpty) {
jsonString = prefs.getString(keyFor);
}
if (jsonString == null || jsonString.isEmpty) {
return {};
}
final Map<String, dynamic> json;
try {
json = jsonDecode(jsonString) as Map<String, dynamic>;
} catch (e) {
appLogger.warn('Stored unread counts are unreadable: $e');
return {};
}
final counts = <String, int>{};
json.forEach((key, value) {
if (value is int) {
counts[key] = value;
} else if (value is num) {
counts[key] = value.toInt();
}
});
return counts;
}
void saveContactUnreadCount(Map<String, int> counts) {
if (publicKeyHex.isEmpty) {
appLogger.warn('Public key hex is not set. Cannot save unread counts.');
return;
}
_pendingContactUnreadCount = counts;
_contactUnreadSaveTimer?.cancel();
_contactUnreadSaveTimer = Timer(_saveDebounceDuration, () async {
if (_pendingContactUnreadCount != null) {
await _flushContactUnreadCount();
}
});
}
Future<void> _flushContactUnreadCount() async {
if (_pendingContactUnreadCount == null) return;
final prefs = PrefsManager.instance;
final jsonStr = jsonEncode(_pendingContactUnreadCount);
await prefs.setString(keyFor, jsonStr);
_pendingContactUnreadCount = null;
}
/// Immediately flush pending writes (call before app termination or disposal)
Future<void> flush() async {
_contactUnreadSaveTimer?.cancel();
await _flushContactUnreadCount();
}
}