Merge zjs81/dev into ez_share_urlimage_PR
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
commit
4000c49213
152 files changed
+28635
-8600
No files matched your search
@@ -313,8 +313,12 @@ class AppSettingsService extends ChangeNotifier {
|
||||
await updateSettings(_settings.copyWith(jumpToOldestUnread: value));
|
||||
}
|
||||
|
||||
Future<void> setImageMessagesEnabled(bool value) async {
|
||||
await updateSettings(_settings.copyWith(imageMessagesEnabled: value));
|
||||
Future<void> setNetworkMapUploadEnabled(bool value) async {
|
||||
await updateSettings(_settings.copyWith(networkMapUploadEnabled: value));
|
||||
}
|
||||
|
||||
Future<void> setNetworkMapPromptShown(bool value) async {
|
||||
await updateSettings(_settings.copyWith(networkMapPromptShown: value));
|
||||
}
|
||||
|
||||
Future<void> setIpfsImageSettings({
|
||||
@@ -335,6 +339,10 @@ class AppSettingsService extends ChangeNotifier {
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> setImageMessagesEnabled(bool value) async {
|
||||
await updateSettings(_settings.copyWith(imageMessagesEnabled: value));
|
||||
}
|
||||
|
||||
/// See [AppSettings.imageProcessAutomatically]. `main.dart` mirrors this into
|
||||
/// `ReceivedImageStore.processAutomatically` on every settings change; the
|
||||
/// store applies it to future arrivals only, so flipping it does not
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -275,14 +275,26 @@ class MapTileCacheResult {
|
||||
final int total;
|
||||
final int downloaded;
|
||||
final int failed;
|
||||
final bool cancelled;
|
||||
|
||||
const MapTileCacheResult({
|
||||
required this.total,
|
||||
required this.downloaded,
|
||||
required this.failed,
|
||||
this.cancelled = false,
|
||||
});
|
||||
}
|
||||
|
||||
/// Cooperative cancellation flag for [MapTileCacheService.downloadRegion].
|
||||
/// Tiles already in flight finish; no new tiles are queued after [cancel].
|
||||
class MapTileDownloadCancelToken {
|
||||
bool _cancelled = false;
|
||||
|
||||
bool get isCancelled => _cancelled;
|
||||
|
||||
void cancel() => _cancelled = true;
|
||||
}
|
||||
|
||||
class CachedTileInfo {
|
||||
final String key;
|
||||
final String host;
|
||||
@@ -316,6 +328,10 @@ class MapTileCacheService extends ChangeNotifier {
|
||||
static const int defaultMinZoom = 10;
|
||||
static const int defaultMaxZoom = 15;
|
||||
|
||||
/// Largest bulk download the UI allows in one go. Keeps a single request
|
||||
/// within tile-server usage policies and avoids filling the device.
|
||||
static const int maxBulkDownloadTiles = 20000;
|
||||
|
||||
final AppSettingsService appSettingsService;
|
||||
final BaseCacheManager cacheManager;
|
||||
late final TileProvider tileProvider;
|
||||
@@ -614,6 +630,7 @@ class MapTileCacheService extends ChangeNotifier {
|
||||
int concurrentDownloads = 8,
|
||||
Map<String, String>? headers,
|
||||
void Function(MapTileCacheProgress progress)? onProgress,
|
||||
MapTileDownloadCancelToken? cancelToken,
|
||||
}) async {
|
||||
final safeMin = math.min(minZoom, maxZoom);
|
||||
final safeMax = math.max(minZoom, maxZoom);
|
||||
@@ -652,10 +669,17 @@ class MapTileCacheService extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
var stoppedEarly = false;
|
||||
|
||||
outer:
|
||||
for (int zoom = safeMin; zoom <= safeMax; zoom++) {
|
||||
final tileBounds = _tileBoundsForBounds(bounds, zoom);
|
||||
for (int x = tileBounds.minX; x <= tileBounds.maxX; x++) {
|
||||
for (int y = tileBounds.minY; y <= tileBounds.maxY; y++) {
|
||||
if (cancelToken?.isCancelled ?? false) {
|
||||
stoppedEarly = true;
|
||||
break outer;
|
||||
}
|
||||
final url = _buildTileUrl(x, y, zoom, urlTemplate: currentTemplate);
|
||||
await queueDownload(url);
|
||||
}
|
||||
@@ -670,6 +694,7 @@ class MapTileCacheService extends ChangeNotifier {
|
||||
total: total,
|
||||
downloaded: completed - failed,
|
||||
failed: failed,
|
||||
cancelled: stoppedEarly,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:latlong2/latlong.dart';
|
||||
|
||||
const String networkMapBaseUrl = 'https://map.meshcoreopen.org';
|
||||
|
||||
/// Largest bbox span the read endpoints accept, in degrees.
|
||||
const double networkMapMaxBboxSpan = 20.0;
|
||||
|
||||
class NetworkMapBbox {
|
||||
final double minLon;
|
||||
final double minLat;
|
||||
final double maxLon;
|
||||
final double maxLat;
|
||||
|
||||
const NetworkMapBbox({
|
||||
required this.minLon,
|
||||
required this.minLat,
|
||||
required this.maxLon,
|
||||
required this.maxLat,
|
||||
});
|
||||
|
||||
bool get isWithinLimit =>
|
||||
maxLon - minLon <= networkMapMaxBboxSpan &&
|
||||
maxLat - minLat <= networkMapMaxBboxSpan;
|
||||
|
||||
/// Valid request boxes for a visible area, or null when it is larger than
|
||||
/// [networkMapMaxBboxSpan]. [west] and [east] may be unwrapped (beyond
|
||||
/// ±180) or wrapped across the antimeridian (west > east); an area that
|
||||
/// crosses ±180 is split into two boxes, one on each side.
|
||||
static List<NetworkMapBbox>? forVisibleArea({
|
||||
required double west,
|
||||
required double south,
|
||||
required double east,
|
||||
required double north,
|
||||
}) {
|
||||
final minLat = south.clamp(-90.0, 90.0);
|
||||
final maxLat = north.clamp(-90.0, 90.0);
|
||||
var span = east - west;
|
||||
if (span < 0) span += 360;
|
||||
if (span > networkMapMaxBboxSpan ||
|
||||
maxLat - minLat > networkMapMaxBboxSpan) {
|
||||
return null;
|
||||
}
|
||||
final w = (west + 180) % 360 - 180; // Dart % is non-negative here.
|
||||
final e = w + span;
|
||||
NetworkMapBbox box(double a, double b) =>
|
||||
NetworkMapBbox(minLon: a, minLat: minLat, maxLon: b, maxLat: maxLat);
|
||||
if (e <= 180) return [box(w, e)];
|
||||
return [box(w, 180), box(-180, e - 360)];
|
||||
}
|
||||
|
||||
String get query => [
|
||||
minLon,
|
||||
minLat,
|
||||
maxLon,
|
||||
maxLat,
|
||||
].map((v) => v.toStringAsFixed(5)).join(',');
|
||||
}
|
||||
|
||||
/// An H3 cell as the server describes it. [boundary] is the open polygon
|
||||
/// (usually six points), so clients need no H3 library.
|
||||
class NetworkMapCell {
|
||||
final String cell;
|
||||
final LatLng center;
|
||||
final List<LatLng> boundary;
|
||||
|
||||
const NetworkMapCell({
|
||||
required this.cell,
|
||||
required this.center,
|
||||
required this.boundary,
|
||||
});
|
||||
|
||||
factory NetworkMapCell.fromJson(Map<String, dynamic> json) {
|
||||
return NetworkMapCell(
|
||||
cell: json['cell'] as String,
|
||||
center: LatLng(
|
||||
(json['lat'] as num).toDouble(),
|
||||
(json['lon'] as num).toDouble(),
|
||||
),
|
||||
boundary: [
|
||||
for (final point in (json['boundary'] as List? ?? const []))
|
||||
LatLng(
|
||||
((point as List)[0] as num).toDouble(),
|
||||
(point[1] as num).toDouble(),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
enum NetworkMapRepeaterStatus { active, recent, stale }
|
||||
|
||||
class NetworkMapRepeater {
|
||||
final String key;
|
||||
final String? name;
|
||||
final int type;
|
||||
final NetworkMapCell cell;
|
||||
final String locationSource;
|
||||
final double confidence;
|
||||
final NetworkMapRepeaterStatus status;
|
||||
final bool confirmed;
|
||||
final int sightings;
|
||||
final DateTime? firstSeen;
|
||||
final DateTime? lastSeen;
|
||||
|
||||
// Only present on the single-repeater endpoint.
|
||||
final int? links;
|
||||
final int? coverageCells;
|
||||
final String? reachableArea;
|
||||
|
||||
const NetworkMapRepeater({
|
||||
required this.key,
|
||||
required this.name,
|
||||
required this.type,
|
||||
required this.cell,
|
||||
required this.locationSource,
|
||||
required this.confidence,
|
||||
required this.status,
|
||||
required this.confirmed,
|
||||
required this.sightings,
|
||||
required this.firstSeen,
|
||||
required this.lastSeen,
|
||||
this.links,
|
||||
this.coverageCells,
|
||||
this.reachableArea,
|
||||
});
|
||||
|
||||
bool get isEstimated => locationSource == 'estimated';
|
||||
|
||||
factory NetworkMapRepeater.fromJson(Map<String, dynamic> json) {
|
||||
return NetworkMapRepeater(
|
||||
key: (json['key'] as String).toLowerCase(),
|
||||
name: json['name'] as String?,
|
||||
type: (json['type'] as num?)?.toInt() ?? 2,
|
||||
cell: NetworkMapCell.fromJson(json['cell'] as Map<String, dynamic>),
|
||||
locationSource: json['locationSource'] as String? ?? 'advert',
|
||||
confidence: (json['confidence'] as num?)?.toDouble() ?? 0,
|
||||
status: NetworkMapRepeaterStatus.values.firstWhere(
|
||||
(s) => s.name == json['status'],
|
||||
orElse: () => NetworkMapRepeaterStatus.stale,
|
||||
),
|
||||
confirmed: json['confirmed'] as bool? ?? false,
|
||||
sightings: (json['sightings'] as num?)?.toInt() ?? 0,
|
||||
firstSeen: _parseTime(json['firstSeen']),
|
||||
lastSeen: _parseTime(json['lastSeen']),
|
||||
links: (json['links'] as num?)?.toInt(),
|
||||
coverageCells: (json['coverageCells'] as num?)?.toInt(),
|
||||
reachableArea: json['reachableArea'] as String?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class NetworkMapLink {
|
||||
final String a;
|
||||
final String b;
|
||||
final NetworkMapCell aCell;
|
||||
final NetworkMapCell bCell;
|
||||
final int packets;
|
||||
final double? snr;
|
||||
final bool confirmed;
|
||||
|
||||
const NetworkMapLink({
|
||||
required this.a,
|
||||
required this.b,
|
||||
required this.aCell,
|
||||
required this.bCell,
|
||||
required this.packets,
|
||||
required this.snr,
|
||||
required this.confirmed,
|
||||
});
|
||||
|
||||
factory NetworkMapLink.fromJson(Map<String, dynamic> json) {
|
||||
return NetworkMapLink(
|
||||
a: (json['a'] as String).toLowerCase(),
|
||||
b: (json['b'] as String).toLowerCase(),
|
||||
aCell: NetworkMapCell.fromJson(json['aCell'] as Map<String, dynamic>),
|
||||
bCell: NetworkMapCell.fromJson(json['bCell'] as Map<String, dynamic>),
|
||||
packets: (json['packets'] as num?)?.toInt() ?? 0,
|
||||
snr: (json['snr'] as num?)?.toDouble(),
|
||||
confirmed: json['confirmed'] as bool? ?? false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
DateTime? _parseTime(Object? value) =>
|
||||
value is String ? DateTime.tryParse(value) : null;
|
||||
|
||||
class NetworkMapApiException implements Exception {
|
||||
final int statusCode;
|
||||
|
||||
const NetworkMapApiException(this.statusCode);
|
||||
|
||||
@override
|
||||
String toString() => 'NetworkMapApiException($statusCode)';
|
||||
}
|
||||
|
||||
/// Read-only client for the network map. Viewing never requires the upload
|
||||
/// opt-in and sends nothing about the radio.
|
||||
class NetworkMapApiClient {
|
||||
final http.Client _client;
|
||||
final String baseUrl;
|
||||
|
||||
NetworkMapApiClient({http.Client? client, this.baseUrl = networkMapBaseUrl})
|
||||
: _client = client ?? http.Client();
|
||||
|
||||
static const Duration _timeout = Duration(seconds: 20);
|
||||
|
||||
Future<List<NetworkMapRepeater>> fetchRepeaters(NetworkMapBbox bbox) async {
|
||||
final json = await _get('/v1/repeaters', {
|
||||
'bbox': bbox.query,
|
||||
'includeUnconfirmed': 'true',
|
||||
});
|
||||
return [
|
||||
for (final item in (json['repeaters'] as List? ?? const []))
|
||||
NetworkMapRepeater.fromJson(item as Map<String, dynamic>),
|
||||
];
|
||||
}
|
||||
|
||||
/// Null when the repeater is unknown or hidden (404).
|
||||
Future<NetworkMapRepeater?> fetchRepeater(String key) async {
|
||||
try {
|
||||
return NetworkMapRepeater.fromJson(
|
||||
await _get('/v1/repeaters/${key.toLowerCase()}', const {}),
|
||||
);
|
||||
} on NetworkMapApiException catch (e) {
|
||||
if (e.statusCode == 404) return null;
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<NetworkMapLink>> fetchLinks(
|
||||
NetworkMapBbox bbox, {
|
||||
String window = '7d',
|
||||
}) async {
|
||||
final json = await _get('/v1/links', {
|
||||
'bbox': bbox.query,
|
||||
'window': window,
|
||||
});
|
||||
return [
|
||||
for (final item in (json['links'] as List? ?? const []))
|
||||
NetworkMapLink.fromJson(item as Map<String, dynamic>),
|
||||
];
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> _get(
|
||||
String path,
|
||||
Map<String, String> query,
|
||||
) async {
|
||||
final uri = Uri.parse(
|
||||
'$baseUrl$path',
|
||||
).replace(queryParameters: query.isEmpty ? null : query);
|
||||
final response = await _client.get(uri).timeout(_timeout);
|
||||
if (response.statusCode != 200) {
|
||||
throw NetworkMapApiException(response.statusCode);
|
||||
}
|
||||
return jsonDecode(utf8.decode(response.bodyBytes)) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
void close() => _client.close();
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export 'network_map_gzip_stub.dart'
|
||||
if (dart.library.io) 'network_map_gzip_io.dart';
|
||||
@@ -0,0 +1,3 @@
|
||||
import 'dart:io';
|
||||
|
||||
List<int>? gzipEncode(List<int> bytes) => gzip.encode(bytes);
|
||||
@@ -0,0 +1,2 @@
|
||||
/// No gzip on web; the server accepts an uncompressed body.
|
||||
List<int>? gzipEncode(List<int> bytes) => null;
|
||||
@@ -0,0 +1,421 @@
|
||||
import 'dart:math';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:cryptography/cryptography.dart';
|
||||
|
||||
import '../../connector/meshcore_protocol.dart';
|
||||
import '../../connector/raw_packet.dart';
|
||||
import '../../utils/location_grid.dart';
|
||||
|
||||
/// Records uploaded to the network map (see the server's API contract).
|
||||
///
|
||||
/// Everything here is built from the packet header, path and signal values
|
||||
/// only. Payloads, MACs, channel hashes, DM hashes, transport codes and exact
|
||||
/// coordinates never make it into a record.
|
||||
|
||||
const String hiddenNodeMarker = '\u{1F6AB}';
|
||||
const int _maxUploadPathBytes = 64;
|
||||
const int _maxAdvertNameBytes = 32;
|
||||
const int _advertPubKeySize = 32;
|
||||
const int _advertSignatureSize = 64;
|
||||
const int _maxAdvertDataSize = 32;
|
||||
|
||||
class NetworkMapLoc {
|
||||
final double lat;
|
||||
final double lon;
|
||||
|
||||
const NetworkMapLoc(this.lat, this.lon);
|
||||
|
||||
factory NetworkMapLoc.snapped(double lat, double lon) {
|
||||
final snapped = snapToLocationGrid(lat, lon);
|
||||
return NetworkMapLoc(snapped.lat, snapped.lon);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {'lat': lat, 'lon': lon};
|
||||
}
|
||||
|
||||
class NetworkMapPreset {
|
||||
final int freqKhz;
|
||||
final double bwKhz;
|
||||
final int sf;
|
||||
final int cr;
|
||||
|
||||
const NetworkMapPreset({
|
||||
required this.freqKhz,
|
||||
required this.bwKhz,
|
||||
required this.sf,
|
||||
required this.cr,
|
||||
});
|
||||
|
||||
static const List<double> _allowedBwKhz = [
|
||||
7.8,
|
||||
10.4,
|
||||
15.6,
|
||||
20.8,
|
||||
31.25,
|
||||
41.7,
|
||||
62.5,
|
||||
125,
|
||||
250,
|
||||
500,
|
||||
];
|
||||
|
||||
/// From the radio's self-info values; null when any is missing or outside
|
||||
/// what the server accepts. Firmware reports frequency in kHz, bandwidth in
|
||||
/// Hz and coding rate as 1–4 or 5–8.
|
||||
static NetworkMapPreset? fromRadio({
|
||||
int? freqKhz,
|
||||
int? bwHz,
|
||||
int? sf,
|
||||
int? cr,
|
||||
}) {
|
||||
if (freqKhz == null || bwHz == null || sf == null || cr == null) {
|
||||
return null;
|
||||
}
|
||||
final bwKhz = _allowedBwKhz.where((bw) => (bw * 1000 - bwHz).abs() < 1);
|
||||
final codingRate = cr <= 4 ? cr + 4 : cr;
|
||||
if (freqKhz < 100000 ||
|
||||
freqKhz > 1100000 ||
|
||||
bwKhz.isEmpty ||
|
||||
sf < 5 ||
|
||||
sf > 12 ||
|
||||
codingRate < 5 ||
|
||||
codingRate > 8) {
|
||||
return null;
|
||||
}
|
||||
return NetworkMapPreset(
|
||||
freqKhz: freqKhz,
|
||||
bwKhz: bwKhz.first,
|
||||
sf: sf,
|
||||
cr: codingRate,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'freqKhz': freqKhz,
|
||||
'bwKhz': bwKhz,
|
||||
'sf': sf,
|
||||
'cr': cr,
|
||||
};
|
||||
}
|
||||
|
||||
class NetworkMapPacketRecord {
|
||||
final int t;
|
||||
final int pt;
|
||||
final int rt;
|
||||
final int hw;
|
||||
final String path;
|
||||
final double snr;
|
||||
final int rssi;
|
||||
final int size;
|
||||
final String h;
|
||||
final bool scoped;
|
||||
|
||||
const NetworkMapPacketRecord({
|
||||
required this.t,
|
||||
required this.pt,
|
||||
required this.rt,
|
||||
required this.hw,
|
||||
required this.path,
|
||||
required this.snr,
|
||||
required this.rssi,
|
||||
required this.size,
|
||||
required this.h,
|
||||
required this.scoped,
|
||||
});
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
't': t,
|
||||
'pt': pt,
|
||||
'rt': rt,
|
||||
'hw': hw,
|
||||
'path': path,
|
||||
'snr': snr,
|
||||
'rssi': rssi,
|
||||
'size': size,
|
||||
'h': h,
|
||||
'scoped': scoped,
|
||||
};
|
||||
}
|
||||
|
||||
class NetworkMapAdvertRecord {
|
||||
final int t;
|
||||
final String key;
|
||||
final int type;
|
||||
final String? name;
|
||||
final NetworkMapLoc? loc;
|
||||
final bool hidden;
|
||||
final double snr;
|
||||
final int rssi;
|
||||
final int rt;
|
||||
final int hw;
|
||||
final String path;
|
||||
|
||||
const NetworkMapAdvertRecord({
|
||||
required this.t,
|
||||
required this.key,
|
||||
required this.type,
|
||||
required this.name,
|
||||
required this.loc,
|
||||
required this.hidden,
|
||||
required this.snr,
|
||||
required this.rssi,
|
||||
required this.rt,
|
||||
required this.hw,
|
||||
required this.path,
|
||||
});
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
't': t,
|
||||
'key': key,
|
||||
'type': type,
|
||||
'name': name,
|
||||
'loc': loc?.toJson(),
|
||||
'hidden': hidden,
|
||||
'snr': snr,
|
||||
'rssi': rssi,
|
||||
'rt': rt,
|
||||
'hw': hw,
|
||||
'path': path,
|
||||
};
|
||||
}
|
||||
|
||||
/// Header, path and signal fields of a `PUSH_CODE_LOG_RX_DATA` frame.
|
||||
class _RxFrame {
|
||||
final double snr;
|
||||
final int rssi;
|
||||
final int rawLength;
|
||||
final int routeType;
|
||||
final int payloadType;
|
||||
final int hashWidth;
|
||||
final Uint8List pathBytes;
|
||||
final Uint8List payload;
|
||||
|
||||
_RxFrame({
|
||||
required this.snr,
|
||||
required this.rssi,
|
||||
required this.rawLength,
|
||||
required this.routeType,
|
||||
required this.payloadType,
|
||||
required this.hashWidth,
|
||||
required this.pathBytes,
|
||||
required this.payload,
|
||||
});
|
||||
|
||||
bool get scoped => routeType == 0 || routeType == 3;
|
||||
|
||||
String get pathHex => _hex(pathBytes);
|
||||
}
|
||||
|
||||
_RxFrame? _parseRxFrame(Uint8List frame) {
|
||||
if (frame.isEmpty || frame[0] != pushCodeLogRxData) return null;
|
||||
try {
|
||||
final reader = BufferReader(frame);
|
||||
reader.skipBytes(1);
|
||||
final snr = reader.readInt8() / 4.0;
|
||||
final rssi = reader.readInt8();
|
||||
final rawLength = reader.remaining;
|
||||
final header = reader.readByte();
|
||||
final routeType = header & 0x03;
|
||||
final payloadType = (header >> 2) & 0x0F;
|
||||
if (routeType == 0 || routeType == 3) {
|
||||
reader.skipBytes(4); // transport codes: never uploaded
|
||||
}
|
||||
final pathLenRaw = reader.readByte();
|
||||
final hashWidth = decodePathHashWidth(pathLenRaw);
|
||||
final pathBytes = reader.readBytes(decodePathByteLen(pathLenRaw));
|
||||
final payload = reader.readBytes(reader.remaining);
|
||||
if (hashWidth > 3 || pathBytes.length > _maxUploadPathBytes) return null;
|
||||
return _RxFrame(
|
||||
snr: snr.clamp(-32.0, 32.0).toDouble(),
|
||||
rssi: rssi.clamp(-200, 0).toInt(),
|
||||
rawLength: rawLength,
|
||||
routeType: routeType,
|
||||
payloadType: payloadType,
|
||||
hashWidth: hashWidth,
|
||||
pathBytes: pathBytes,
|
||||
payload: payload,
|
||||
);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Unix seconds rounded down to the minute.
|
||||
int networkMapMinute(DateTime time) {
|
||||
final seconds = time.millisecondsSinceEpoch ~/ 1000;
|
||||
return seconds - seconds % 60;
|
||||
}
|
||||
|
||||
/// Raw packet length rounded up to a multiple of 16, capped at 256.
|
||||
int roundUpPacketSize(int length) {
|
||||
final rounded = ((length + 15) ~/ 16) * 16;
|
||||
return rounded > 256 ? 256 : rounded;
|
||||
}
|
||||
|
||||
/// Header-only packet record for a received 0x88 frame, or null when the
|
||||
/// frame is malformed or outside what the server accepts.
|
||||
NetworkMapPacketRecord? buildPacketRecord(
|
||||
Uint8List frame,
|
||||
DateTime receivedAt,
|
||||
) {
|
||||
final rx = _parseRxFrame(frame);
|
||||
if (rx == null) return null;
|
||||
return NetworkMapPacketRecord(
|
||||
t: networkMapMinute(receivedAt),
|
||||
pt: rx.payloadType,
|
||||
rt: rx.routeType,
|
||||
hw: rx.hashWidth,
|
||||
path: rx.pathHex,
|
||||
snr: rx.snr,
|
||||
rssi: rx.rssi,
|
||||
size: roundUpPacketSize(rx.rawLength),
|
||||
h: computePacketHash(rx.payloadType, rx.payload),
|
||||
scoped: rx.scoped,
|
||||
);
|
||||
}
|
||||
|
||||
/// Advert record for a received repeater or room server advert whose Ed25519
|
||||
/// signature verifies. Chat and sensor adverts, unsigned or malformed adverts
|
||||
/// and anything that isn't an advert return null.
|
||||
Future<NetworkMapAdvertRecord?> buildAdvertRecord(
|
||||
Uint8List frame,
|
||||
DateTime receivedAt,
|
||||
) async {
|
||||
final rx = _parseRxFrame(frame);
|
||||
if (rx == null || rx.payloadType != payloadTypeADVERT) return null;
|
||||
final payload = rx.payload;
|
||||
const appDataStart = _advertPubKeySize + 4 + _advertSignatureSize;
|
||||
if (payload.length <= appDataStart) return null;
|
||||
|
||||
// Only the first 32 app-data bytes are signed (firmware Mesh.cpp truncates
|
||||
// to MAX_ADVERT_DATA_SIZE before verifying and parsing), so bytes appended
|
||||
// after them must never reach the name, location or 🚫 check.
|
||||
final appData = payload.sublist(
|
||||
appDataStart,
|
||||
min(payload.length, appDataStart + _maxAdvertDataSize),
|
||||
);
|
||||
final flags = appData[0];
|
||||
final type = flags & 0x0F;
|
||||
if (type != advTypeRepeater && type != advTypeRoom) return null;
|
||||
|
||||
final publicKey = payload.sublist(0, _advertPubKeySize);
|
||||
if (!await _verifyAdvertSignature(payload, publicKey)) return null;
|
||||
|
||||
// Same layout as the firmware's AdvertDataParser.
|
||||
var i = 1;
|
||||
NetworkMapLoc? loc;
|
||||
if (flags & 0x10 != 0) {
|
||||
if (appData.length < i + 8) return null;
|
||||
final view = ByteData.sublistView(appData);
|
||||
final lat = view.getInt32(i, Endian.little) / 1e6;
|
||||
final lon = view.getInt32(i + 4, Endian.little) / 1e6;
|
||||
i += 8;
|
||||
if (_isPlausibleLocation(lat, lon)) loc = NetworkMapLoc.snapped(lat, lon);
|
||||
}
|
||||
if (flags & 0x20 != 0) i += 2;
|
||||
if (flags & 0x40 != 0) i += 2;
|
||||
String? name;
|
||||
if (flags & 0x80 != 0 && appData.length > i) {
|
||||
var nameBytes = appData.sublist(i);
|
||||
final nul = nameBytes.indexOf(0);
|
||||
if (nul >= 0) nameBytes = nameBytes.sublist(0, nul);
|
||||
final decoded = utf8.decode(nameBytes, allowMalformed: true);
|
||||
if (decoded.isNotEmpty) name = decoded;
|
||||
}
|
||||
|
||||
final hidden = name != null && name.contains(hiddenNodeMarker);
|
||||
return NetworkMapAdvertRecord(
|
||||
t: networkMapMinute(receivedAt),
|
||||
key: _hex(publicKey),
|
||||
type: type,
|
||||
name: hidden || name == null
|
||||
? null
|
||||
: _truncateUtf8(name, _maxAdvertNameBytes),
|
||||
loc: hidden ? null : loc,
|
||||
hidden: hidden,
|
||||
snr: rx.snr,
|
||||
rssi: rx.rssi,
|
||||
rt: rx.routeType,
|
||||
hw: rx.hashWidth,
|
||||
path: rx.pathHex,
|
||||
);
|
||||
}
|
||||
|
||||
/// The firmware signs pubkey ‖ timestamp ‖ app_data (app_data capped at
|
||||
/// MAX_ADVERT_DATA_SIZE), see Mesh::createAdvert.
|
||||
Future<bool> _verifyAdvertSignature(
|
||||
Uint8List payload,
|
||||
Uint8List publicKey,
|
||||
) async {
|
||||
const sigStart = _advertPubKeySize + 4;
|
||||
const appDataStart = sigStart + _advertSignatureSize;
|
||||
var appDataEnd = payload.length;
|
||||
if (appDataEnd - appDataStart > _maxAdvertDataSize) {
|
||||
appDataEnd = appDataStart + _maxAdvertDataSize;
|
||||
}
|
||||
final message = <int>[
|
||||
...payload.sublist(0, sigStart),
|
||||
...payload.sublist(appDataStart, appDataEnd),
|
||||
];
|
||||
try {
|
||||
return await Ed25519().verify(
|
||||
message,
|
||||
signature: Signature(
|
||||
payload.sublist(sigStart, appDataStart),
|
||||
publicKey: SimplePublicKey(publicKey, type: KeyPairType.ed25519),
|
||||
),
|
||||
);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool _isPlausibleLocation(double lat, double lon) {
|
||||
const epsilon = 1e-6;
|
||||
return (lat.abs() > epsilon || lon.abs() > epsilon) &&
|
||||
lat >= -90 &&
|
||||
lat <= 90 &&
|
||||
lon >= -180 &&
|
||||
lon <= 180;
|
||||
}
|
||||
|
||||
String _truncateUtf8(String value, int maxBytes) {
|
||||
if (utf8.encode(value).length <= maxBytes) return value;
|
||||
final buffer = StringBuffer();
|
||||
var used = 0;
|
||||
for (final rune in value.runes) {
|
||||
final char = String.fromCharCode(rune);
|
||||
final length = utf8.encode(char).length;
|
||||
if (used + length > maxBytes) break;
|
||||
buffer.write(char);
|
||||
used += length;
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
String _hex(List<int> bytes) =>
|
||||
bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
/// The `POST /v1/upload` body. Field names and nesting follow the contract
|
||||
/// exactly; the server rejects unknown fields.
|
||||
Map<String, dynamic> buildUploadBody({
|
||||
required String installId,
|
||||
required String app,
|
||||
required NetworkMapLoc? loc,
|
||||
required NetworkMapPreset? preset,
|
||||
required int listenSeconds,
|
||||
required List<NetworkMapPacketRecord> packets,
|
||||
required List<NetworkMapAdvertRecord> adverts,
|
||||
}) => {
|
||||
'v': 1,
|
||||
'installId': installId,
|
||||
'token': null,
|
||||
'app': app,
|
||||
'loc': loc?.toJson(),
|
||||
'preset': preset?.toJson(),
|
||||
'listenSeconds': listenSeconds.clamp(0, 600),
|
||||
'packets': [for (final p in packets) p.toJson()],
|
||||
'adverts': [for (final a in adverts) a.toJson()],
|
||||
};
|
||||
@@ -0,0 +1,413 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../connector/meshcore_connector.dart';
|
||||
import '../../connector/meshcore_protocol.dart';
|
||||
import '../../storage/prefs_manager.dart';
|
||||
import '../../utils/app_logger.dart';
|
||||
import '../app_settings_service.dart';
|
||||
import 'network_map_api_client.dart';
|
||||
import 'network_map_gzip.dart';
|
||||
import 'network_map_records.dart';
|
||||
|
||||
/// Random per-install identifier, regenerated every 24 h and never derived
|
||||
/// from the radio key.
|
||||
class NetworkMapInstallId {
|
||||
static const _keyId = 'network_map_install_id';
|
||||
static const _keyCreatedAt = 'network_map_install_id_created_at';
|
||||
static const Duration lifetime = Duration(hours: 24);
|
||||
|
||||
final SharedPreferences _prefs;
|
||||
final DateTime Function() _now;
|
||||
final Random _random;
|
||||
|
||||
NetworkMapInstallId(this._prefs, {DateTime Function()? now, Random? random})
|
||||
: _now = now ?? DateTime.now,
|
||||
_random = random ?? Random.secure();
|
||||
|
||||
String current() {
|
||||
final now = _now();
|
||||
final id = _prefs.getString(_keyId);
|
||||
final createdMs = _prefs.getInt(_keyCreatedAt);
|
||||
if (id != null && createdMs != null) {
|
||||
final age = now.difference(
|
||||
DateTime.fromMillisecondsSinceEpoch(createdMs),
|
||||
);
|
||||
if (!age.isNegative && age < lifetime) return id;
|
||||
}
|
||||
final bytes = Uint8List.fromList(
|
||||
List<int>.generate(16, (_) => _random.nextInt(256)),
|
||||
);
|
||||
final fresh = base64Url.encode(bytes).replaceAll('=', '');
|
||||
unawaited(_prefs.setString(_keyId, fresh));
|
||||
unawaited(_prefs.setInt(_keyCreatedAt, now.millisecondsSinceEpoch));
|
||||
return fresh;
|
||||
}
|
||||
}
|
||||
|
||||
class _Queued<T> {
|
||||
final DateTime queuedAt;
|
||||
final T record;
|
||||
|
||||
_Queued(this.queuedAt, this.record);
|
||||
}
|
||||
|
||||
/// Records waiting for upload, with the contract's batch caps and age limit.
|
||||
class NetworkMapUploadQueue {
|
||||
static const int maxPacketsPerBatch = 2000;
|
||||
static const int maxAdvertsPerBatch = 200;
|
||||
static const Duration maxQueueAge = Duration(hours: 1);
|
||||
|
||||
/// The server drops records more than 65 min old, so anything past an hour
|
||||
/// is not worth sending.
|
||||
static const Duration maxRecordAge = Duration(minutes: 60);
|
||||
|
||||
// Bounds memory if uploads keep failing for the full hour.
|
||||
static const int _maxQueuedPackets = maxPacketsPerBatch * 5;
|
||||
|
||||
final List<_Queued<NetworkMapPacketRecord>> _packets = [];
|
||||
final List<_Queued<NetworkMapAdvertRecord>> _adverts = [];
|
||||
|
||||
bool get isEmpty => _packets.isEmpty && _adverts.isEmpty;
|
||||
int get packetCount => _packets.length;
|
||||
int get advertCount => _adverts.length;
|
||||
|
||||
void addPacket(NetworkMapPacketRecord record, DateTime now) {
|
||||
_packets.add(_Queued(now, record));
|
||||
if (_packets.length > _maxQueuedPackets) _packets.removeAt(0);
|
||||
}
|
||||
|
||||
void addAdvert(NetworkMapAdvertRecord record, DateTime now) {
|
||||
// Only the latest advert per key is useful within one batch window.
|
||||
_adverts.removeWhere((q) => q.record.key == record.key);
|
||||
_adverts.add(_Queued(now, record));
|
||||
}
|
||||
|
||||
void dropExpired(DateTime now) {
|
||||
final cutoffSeconds = networkMapMinute(now.subtract(maxRecordAge));
|
||||
bool expired(DateTime queuedAt, int t) =>
|
||||
now.difference(queuedAt) > maxQueueAge || t < cutoffSeconds;
|
||||
_packets.removeWhere((q) => expired(q.queuedAt, q.record.t));
|
||||
_adverts.removeWhere((q) => expired(q.queuedAt, q.record.t));
|
||||
}
|
||||
|
||||
void clear() {
|
||||
_packets.clear();
|
||||
_adverts.clear();
|
||||
}
|
||||
|
||||
/// The oldest records up to the per-batch caps. They stay queued until
|
||||
/// [remove] confirms the upload.
|
||||
({List<NetworkMapPacketRecord> packets, List<NetworkMapAdvertRecord> adverts})
|
||||
peekBatch() => (
|
||||
packets: [for (final q in _packets.take(maxPacketsPerBatch)) q.record],
|
||||
adverts: [for (final q in _adverts.take(maxAdvertsPerBatch)) q.record],
|
||||
);
|
||||
|
||||
void remove(int packets, int adverts) {
|
||||
_packets.removeRange(0, min(packets, _packets.length));
|
||||
_adverts.removeRange(0, min(adverts, _adverts.length));
|
||||
}
|
||||
}
|
||||
|
||||
/// Opt-in uploader for the network map.
|
||||
///
|
||||
/// Listens to raw RX log frames only while the user has opted in and a radio
|
||||
/// is connected, and uploads header-only records in batches.
|
||||
class NetworkMapUploadService extends ChangeNotifier {
|
||||
static const Duration uploadInterval = Duration(seconds: 60);
|
||||
static const Duration heartbeatInterval = Duration(minutes: 5);
|
||||
static const Duration maxBackoff = Duration(minutes: 15);
|
||||
static const int _maxJitterMs = 10000;
|
||||
|
||||
static const _keySentDay = 'network_map_sent_day';
|
||||
static const _keySentCount = 'network_map_sent_count';
|
||||
static const _keyLastUpload = 'network_map_last_upload';
|
||||
|
||||
final MeshCoreConnector _connector;
|
||||
final AppSettingsService _settings;
|
||||
final http.Client _client;
|
||||
final String baseUrl;
|
||||
final Random _random = Random();
|
||||
final NetworkMapUploadQueue _queue = NetworkMapUploadQueue();
|
||||
|
||||
StreamSubscription<Uint8List>? _frameSub;
|
||||
Timer? _timer;
|
||||
bool _uploading = false;
|
||||
|
||||
/// Bumped whenever sharing is turned off. An upload started under an older
|
||||
/// generation is never sent and its result is ignored, so nothing leaves the
|
||||
/// phone after consent is withdrawn and a late response can't touch a queue
|
||||
/// that was cleared and refilled in the meantime.
|
||||
int _consentGeneration = 0;
|
||||
int _failures = 0;
|
||||
Duration _retryAfter = Duration.zero;
|
||||
Duration _nextInterval = uploadInterval;
|
||||
DateTime? _listenMark;
|
||||
int _listenSeconds = 0;
|
||||
DateTime? _lastUploadAt;
|
||||
DateTime? _lastAttemptAt;
|
||||
int _packetsSentToday = 0;
|
||||
String? _appId;
|
||||
|
||||
NetworkMapUploadService({
|
||||
required MeshCoreConnector connector,
|
||||
required AppSettingsService settings,
|
||||
http.Client? client,
|
||||
this.baseUrl = networkMapBaseUrl,
|
||||
}) : _connector = connector,
|
||||
_settings = settings,
|
||||
_client = client ?? http.Client() {
|
||||
_loadStatus();
|
||||
_connector.addListener(_sync);
|
||||
_settings.addListener(_sync);
|
||||
_sync();
|
||||
}
|
||||
|
||||
bool get enabled => _settings.settings.networkMapUploadEnabled;
|
||||
|
||||
/// True while frames are being collected.
|
||||
bool get isActive => _frameSub != null;
|
||||
DateTime? get lastUploadAt => _lastUploadAt;
|
||||
int get packetsSentToday {
|
||||
final prefs = PrefsManager.instance;
|
||||
return prefs.getString(_keySentDay) == _dayKey(DateTime.now())
|
||||
? _packetsSentToday
|
||||
: 0;
|
||||
}
|
||||
|
||||
Future<void> setEnabled(bool value) =>
|
||||
_settings.setNetworkMapUploadEnabled(value);
|
||||
|
||||
void _loadStatus() {
|
||||
final prefs = PrefsManager.instance;
|
||||
final lastMs = prefs.getInt(_keyLastUpload);
|
||||
if (lastMs != null) {
|
||||
_lastUploadAt = DateTime.fromMillisecondsSinceEpoch(lastMs);
|
||||
}
|
||||
_packetsSentToday = prefs.getInt(_keySentCount) ?? 0;
|
||||
}
|
||||
|
||||
void _sync() {
|
||||
if (!enabled && (isActive || !_queue.isEmpty || _uploading)) {
|
||||
_queue.clear();
|
||||
_consentGeneration++;
|
||||
}
|
||||
// The store-review demo radio is simulated; its traffic must not reach
|
||||
// the real map.
|
||||
final shouldListen =
|
||||
enabled && _connector.isConnected && !_connector.isReviewMode;
|
||||
if (shouldListen == isActive) return;
|
||||
if (shouldListen) {
|
||||
_frameSub = _connector.receivedFrames.listen(_onFrame);
|
||||
_listenMark = DateTime.now();
|
||||
_lastAttemptAt ??= DateTime.now();
|
||||
_schedule(uploadInterval);
|
||||
} else {
|
||||
_accrueListenTime();
|
||||
_listenMark = null;
|
||||
unawaited(_frameSub?.cancel());
|
||||
_frameSub = null;
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _onFrame(Uint8List frame) {
|
||||
if (frame.isEmpty || frame[0] != pushCodeLogRxData) return;
|
||||
final now = DateTime.now();
|
||||
final packet = buildPacketRecord(frame, now);
|
||||
if (packet == null) return;
|
||||
_queue.addPacket(packet, now);
|
||||
if (packet.pt == payloadTypeADVERT) {
|
||||
unawaited(
|
||||
buildAdvertRecord(frame, now).then((advert) {
|
||||
if (advert != null && isActive) _queue.addAdvert(advert, now);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _accrueListenTime() {
|
||||
final mark = _listenMark;
|
||||
if (mark == null) return;
|
||||
final now = DateTime.now();
|
||||
_listenSeconds += now.difference(mark).inSeconds;
|
||||
_listenMark = now;
|
||||
}
|
||||
|
||||
void _schedule(Duration base) {
|
||||
_timer?.cancel();
|
||||
final jitter = Duration(milliseconds: _random.nextInt(_maxJitterMs + 1));
|
||||
_timer = Timer(base + jitter, _tick);
|
||||
}
|
||||
|
||||
Future<void> _tick() async {
|
||||
if (!isActive || _uploading) return;
|
||||
final now = DateTime.now();
|
||||
_queue.dropExpired(now);
|
||||
final sinceLast = now.difference(_lastAttemptAt ?? now);
|
||||
if (_queue.isEmpty && sinceLast < heartbeatInterval) {
|
||||
_schedule(_nextInterval);
|
||||
return;
|
||||
}
|
||||
await _upload();
|
||||
if (isActive) {
|
||||
_schedule(_failures == 0 ? _nextInterval : _backoffDelay);
|
||||
}
|
||||
}
|
||||
|
||||
Duration get _backoffDelay {
|
||||
final exp = uploadInterval * pow(2, _failures - 1).toInt();
|
||||
final delay = exp > maxBackoff ? maxBackoff : exp;
|
||||
return _retryAfter > delay ? _retryAfter : delay;
|
||||
}
|
||||
|
||||
Future<void> _upload() async {
|
||||
_uploading = true;
|
||||
final generation = _consentGeneration;
|
||||
bool stale() => generation != _consentGeneration || !enabled;
|
||||
_lastAttemptAt = DateTime.now();
|
||||
try {
|
||||
_accrueListenTime();
|
||||
final batch = _queue.peekBatch();
|
||||
final lat = _connector.selfLatitude;
|
||||
final lon = _connector.selfLongitude;
|
||||
final hasPosition =
|
||||
lat != null &&
|
||||
lon != null &&
|
||||
(lat.abs() > 1e-6 || lon.abs() > 1e-6) &&
|
||||
lat.abs() <= 90 &&
|
||||
lon.abs() <= 180;
|
||||
final body = buildUploadBody(
|
||||
installId: NetworkMapInstallId(PrefsManager.instance).current(),
|
||||
app: await _appString(),
|
||||
loc: hasPosition ? NetworkMapLoc.snapped(lat, lon) : null,
|
||||
preset: NetworkMapPreset.fromRadio(
|
||||
freqKhz: _connector.currentFreqHz,
|
||||
bwHz: _connector.currentBwHz,
|
||||
sf: _connector.currentSf,
|
||||
cr: _connector.currentCr,
|
||||
),
|
||||
listenSeconds: min(_listenSeconds, 600),
|
||||
packets: batch.packets,
|
||||
adverts: batch.adverts,
|
||||
);
|
||||
if (stale()) return;
|
||||
final jsonBytes = utf8.encode(jsonEncode(body));
|
||||
final gzipped = gzipEncode(jsonBytes);
|
||||
final response = await _client
|
||||
.post(
|
||||
Uri.parse('$baseUrl/v1/upload'),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
if (gzipped != null) 'Content-Encoding': 'gzip',
|
||||
},
|
||||
body: gzipped ?? jsonBytes,
|
||||
)
|
||||
.timeout(const Duration(seconds: 30));
|
||||
if (stale()) return;
|
||||
final status = response.statusCode;
|
||||
if (status == 202 || status == 200) {
|
||||
_queue.remove(batch.packets.length, batch.adverts.length);
|
||||
_onUploaded(batch.packets.length, response.body);
|
||||
} else if (status == 429 || status >= 500) {
|
||||
_onFailed(response.headers['retry-after'], response.body);
|
||||
} else {
|
||||
// 400/413/415: resending the same batch can never succeed.
|
||||
appLogger.warn(
|
||||
'Network map upload rejected ($status): ${response.body}',
|
||||
tag: 'NetworkMap',
|
||||
);
|
||||
_queue.remove(batch.packets.length, batch.adverts.length);
|
||||
_listenSeconds = 0;
|
||||
_failures = 0;
|
||||
}
|
||||
} catch (e) {
|
||||
if (stale()) return;
|
||||
appLogger.warn('Network map upload failed: $e', tag: 'NetworkMap');
|
||||
_onFailed(null, null);
|
||||
} finally {
|
||||
_uploading = false;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
void _onUploaded(int packetCount, String body) {
|
||||
final now = DateTime.now();
|
||||
_failures = 0;
|
||||
_retryAfter = Duration.zero;
|
||||
_listenSeconds = 0;
|
||||
_lastUploadAt = now;
|
||||
_nextInterval = uploadInterval;
|
||||
try {
|
||||
final next = (jsonDecode(body) as Map)['nextUploadSeconds'];
|
||||
if (next is num && next >= 30 && next <= 900) {
|
||||
_nextInterval = Duration(seconds: next.toInt());
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
final prefs = PrefsManager.instance;
|
||||
final today = _dayKey(now);
|
||||
if (prefs.getString(_keySentDay) != today) _packetsSentToday = 0;
|
||||
_packetsSentToday += packetCount;
|
||||
unawaited(prefs.setString(_keySentDay, today));
|
||||
unawaited(prefs.setInt(_keySentCount, _packetsSentToday));
|
||||
unawaited(prefs.setInt(_keyLastUpload, now.millisecondsSinceEpoch));
|
||||
}
|
||||
|
||||
void _onFailed(String? retryAfterHeader, String? body) {
|
||||
_failures++;
|
||||
var retryAfter = int.tryParse(retryAfterHeader?.trim() ?? '');
|
||||
if (retryAfter == null && body != null) {
|
||||
try {
|
||||
final value = (jsonDecode(body) as Map)['retryAfterSeconds'];
|
||||
if (value is num) retryAfter = value.toInt();
|
||||
} catch (_) {}
|
||||
}
|
||||
_retryAfter = retryAfter == null
|
||||
? Duration.zero
|
||||
: Duration(seconds: min(retryAfter, maxBackoff.inSeconds));
|
||||
}
|
||||
|
||||
@visibleForTesting
|
||||
int get queuedPacketCount => _queue.packetCount;
|
||||
|
||||
@visibleForTesting
|
||||
void queuePacketForTest(NetworkMapPacketRecord record) =>
|
||||
_queue.addPacket(record, DateTime.now());
|
||||
|
||||
@visibleForTesting
|
||||
Future<void> uploadNowForTest() => _upload();
|
||||
|
||||
Future<String> _appString() async {
|
||||
if (_appId != null) return _appId!;
|
||||
var version = '';
|
||||
try {
|
||||
version = (await PackageInfo.fromPlatform()).version;
|
||||
} catch (_) {}
|
||||
final cleaned = version.replaceAll(RegExp(r'[^\x21-\x7E]'), '');
|
||||
final id = cleaned.isEmpty ? 'meshcore-open' : 'meshcore-open/$cleaned';
|
||||
return _appId = id.length > 64 ? id.substring(0, 64) : id;
|
||||
}
|
||||
|
||||
static String _dayKey(DateTime time) =>
|
||||
'${time.year}-${time.month}-${time.day}';
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_connector.removeListener(_sync);
|
||||
_settings.removeListener(_sync);
|
||||
_timer?.cancel();
|
||||
unawaited(_frameSub?.cancel());
|
||||
_client.close();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
///
|
||||
|
||||
@@ -131,6 +131,14 @@ class RepeaterCommandService {
|
||||
);
|
||||
}
|
||||
|
||||
/// The text [sendCommand] would put on the wire for its next attempt: the
|
||||
/// clock-sync rewrite plus the `XX|` reply prefix (unless [raw]). Used for
|
||||
/// debug previews so they match what is actually sent.
|
||||
String previewFramedCommand(String command, {bool raw = false}) {
|
||||
if (raw) return command;
|
||||
return '${_peekPrefixToken()}${normalizeRepeaterClockSyncCommand(command)}';
|
||||
}
|
||||
|
||||
/// Send [line] verbatim and don't wait for a reply. While `region load` is
|
||||
/// active the firmware consumes each line before prefix stripping and
|
||||
/// sends nothing back (simple_repeater/MyMesh.cpp handleCommand).
|
||||
@@ -185,6 +193,17 @@ class RepeaterCommandService {
|
||||
_pendingByPrefix.clear();
|
||||
}
|
||||
|
||||
String _peekPrefixToken() {
|
||||
for (var i = 0; i < 256; i++) {
|
||||
final value = (_prefixCounter + i) & 0xFF;
|
||||
final token = '${value.toRadixString(16).padLeft(2, '0').toUpperCase()}|';
|
||||
if (!_pendingByPrefix.containsKey(token)) {
|
||||
return token;
|
||||
}
|
||||
}
|
||||
return '00|';
|
||||
}
|
||||
|
||||
String _nextPrefixToken() {
|
||||
for (var i = 0; i < 256; i++) {
|
||||
final value = _prefixCounter++ & 0xFF;
|
||||
|
||||
@@ -9,6 +9,10 @@ const String contactsAllGroupsValue = '__all__';
|
||||
|
||||
enum ChannelSortOption { manual, name, latestMessages, unread }
|
||||
|
||||
/// Which nodes the map draws: the radio's own contacts, the online network
|
||||
/// map, or both.
|
||||
enum MapSourceOption { local, online, both }
|
||||
|
||||
class UiViewStateService extends ChangeNotifier {
|
||||
static const _keyContactsSelectedGroupName = 'ui_contacts_selected_group';
|
||||
static const _keyContactsSortOption = 'ui_contacts_sort_option';
|
||||
@@ -16,6 +20,7 @@ class UiViewStateService extends ChangeNotifier {
|
||||
static const _keyContactsTypeFilter = 'ui_contacts_type_filter';
|
||||
static const _keyChannelsSortOption = 'ui_channels_sort_option';
|
||||
static const _keyChannelsSortIndexLegacy = 'ui_channels_sort_index';
|
||||
static const _keyMapSource = 'ui_map_source';
|
||||
|
||||
String _contactsSelectedGroupName = contactsAllGroupsValue;
|
||||
String _contactsSearchText = '';
|
||||
@@ -26,6 +31,7 @@ class UiViewStateService extends ChangeNotifier {
|
||||
|
||||
String _channelsSearchText = '';
|
||||
ChannelSortOption _channelsSortOption = ChannelSortOption.manual;
|
||||
MapSourceOption _mapSource = MapSourceOption.local;
|
||||
|
||||
String get contactsSelectedGroupName => _contactsSelectedGroupName;
|
||||
String get contactsSearchText => _contactsSearchText;
|
||||
@@ -35,6 +41,7 @@ class UiViewStateService extends ChangeNotifier {
|
||||
ContactTypeFilter get contactsTypeFilter => _contactsTypeFilter;
|
||||
String get channelsSearchText => _channelsSearchText;
|
||||
ChannelSortOption get channelsSortOption => _channelsSortOption;
|
||||
MapSourceOption get mapSource => _mapSource;
|
||||
|
||||
Future<void> initialize() async {
|
||||
final prefs = PrefsManager.instance;
|
||||
@@ -63,6 +70,14 @@ class UiViewStateService extends ChangeNotifier {
|
||||
);
|
||||
}
|
||||
|
||||
final mapSourceStr = prefs.getString(_keyMapSource);
|
||||
if (mapSourceStr != null) {
|
||||
_mapSource = MapSourceOption.values.firstWhere(
|
||||
(e) => e.name == mapSourceStr,
|
||||
orElse: () => MapSourceOption.local,
|
||||
);
|
||||
}
|
||||
|
||||
final channelSortStr = prefs.getString(_keyChannelsSortOption);
|
||||
if (channelSortStr != null) {
|
||||
_channelsSortOption = ChannelSortOption.values.firstWhere(
|
||||
@@ -151,4 +166,11 @@ class UiViewStateService extends ChangeNotifier {
|
||||
PrefsManager.instance.setString(_keyChannelsSortOption, value.name),
|
||||
);
|
||||
}
|
||||
|
||||
void setMapSource(MapSourceOption value) {
|
||||
if (_mapSource == value) return;
|
||||
_mapSource = value;
|
||||
notifyListeners();
|
||||
unawaited(PrefsManager.instance.setString(_keyMapSource, value.name));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user