diff --git a/README.md b/README.md index 889370e8..6f3dc5d3 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ See the [user documentation](documentation/README.md), [connection guide](docume - **Contact Groups**: Create custom groups to organize your mesh network contacts - **Message Reactions**: React to messages with emoji responses - **Message Replies**: Thread conversations with inline reply functionality -- **Android Auto & Watches**: Hear messages and reply by voice in Android Auto, or reply from the notification shade and Wear OS/Galaxy watches ([guide](documentation/notifications.md#android-auto)) +- **Android Auto & Watches**: Reply from the notification shade and Wear OS/Galaxy watches, or hear messages and reply by voice in Android Auto (optional build flag) ([guide](documentation/notifications.md#android-auto)) - **Channel Muting**: Mute a channel from its chat screen, the channel list, or its notification ### Mesh Network @@ -171,7 +171,7 @@ See the [user documentation](documentation/README.md), [connection guide](docume | Map & Location | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Device Management | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Repeater Hub | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -| Notification replies | ✅
(incl. Android Auto, watches) | ❌ | ❌ | ❌ | ❌ | ❌ | +| Notification replies | ✅
(incl. watches; Android Auto optional) | ❌ | ❌ | ❌ | ❌ | ❌ | The matrix describes implemented functionality, not a guarantee that every feature has been tested on every device. Web device connections use Web Serial and require Chrome and a secure origin. Image inference and translation require native runtimes and are unavailable on web. Android APKs currently include only `arm64-v8a`; the minimum Android API follows the Flutter SDK used to build. @@ -296,7 +296,7 @@ Messages are transmitted as binary frames using a custom protocol optimized for - **Theme**: System default, light, or dark mode - **Language**: Use one of 18 languages (English, Chinese, French, Spanish, Portuguese, German, Dutch, Polish, Swedish, Italian, Slovak, Slovenian, Bulgarian, Russian, Ukrainian, Hungarian, Japanese, Korean) -- **Notifications**: Configurable for messages, channels, and node advertisements; per-channel muting; reply, mark-as-read, and mute actions on Android notifications and watches (reply and mark-as-read in Android Auto) +- **Notifications**: Configurable for messages, channels, and node advertisements; per-channel muting; reply, mark-as-read, and mute actions on Android notifications and watches (reply and mark-as-read in Android Auto when built with `--android-project-arg=androidAuto=true`) - **Battery Chemistry**: Support for NMC, LiFePO4, LiPo, and LiPo HV battery types - **Message Retry**: Automatic retry with configurable path clearing diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 4bc45a97..96e61afb 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -106,6 +106,24 @@ android { // } } +// Android Auto (notification read-aloud and voice reply) is opt-in, because +// declaring it puts the app through Play's separate Android Auto review. +// Enable it with `flutter build apk --android-project-arg=androidAuto=true` +// or `./gradlew -PandroidAuto=true ...`. +val androidAutoEnabled = (findProperty("androidAuto") as String?)?.toBoolean() == true + +if (androidAutoEnabled) { + android.sourceSets.getByName("main").res.srcDir("src/androidAuto/res") +} + +androidComponents { + onVariants { variant -> + if (androidAutoEnabled) { + variant.sources.manifests.addStaticManifestFile("src/androidAuto/AndroidManifest.xml") + } + } +} + flutter { source = "../.." } diff --git a/android/app/src/androidAuto/AndroidManifest.xml b/android/app/src/androidAuto/AndroidManifest.xml new file mode 100644 index 00000000..4c5db2aa --- /dev/null +++ b/android/app/src/androidAuto/AndroidManifest.xml @@ -0,0 +1,9 @@ + + + + + + + diff --git a/android/app/src/main/res/xml/automotive_app_desc.xml b/android/app/src/androidAuto/res/xml/automotive_app_desc.xml similarity index 100% rename from android/app/src/main/res/xml/automotive_app_desc.xml rename to android/app/src/androidAuto/res/xml/automotive_app_desc.xml diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 0d27210f..f25683d7 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -46,10 +46,6 @@ android:name="android.appwidget.provider" android:resource="@xml/unread_widget_info" /> - - ` URI to clipboard | | Share Contact Zero-Hop | All types | Broadcasts the contact's advertisement one hop | -| Delete Contact | All types | Confirmation dialog → removes from device and clears messages | +| Delete Contact | All types | Confirmation dialog → removes from device and clears messages. If auto-add is on for that type, the radio adds it back the next time it advertises; the dialog warns about this | ## App Bar Menus diff --git a/documentation/map-and-location.md b/documentation/map-and-location.md index 3cfa7a6f..634235ef 100644 --- a/documentation/map-and-location.md +++ b/documentation/map-and-location.md @@ -103,10 +103,18 @@ Shows node count and pin count. Tappable to expand a legend of all marker types. ## Path Trace Map ### How to Access -- From the main map's radar icon +- From the main map's menu → **Path Trace** (build your own route, see below) - From a contact's long-press menu → "Path Trace / Ping" - From a message's path view → radar icon +### Building a Custom Trace on the Map +1. Open the map menu and choose **Path Trace**. A panel appears at the top of the map. +2. Tap nodes on the map in the order the trace should travel. **Remove Last** and **Clear** edit the list. +3. Choose **Round trip** (the trace comes back along the same hops) or **As entered** (the hops are used exactly as listed, so add the return hops yourself). +4. Tap **Run path trace**. Nothing is sent until you press this button. + +Returning from the result keeps your hops, mode and the last result (**View last result** reopens it without sending again). **Close** or the back button hides the panel without discarding the hops; reopening **Path Trace** during the same session resumes where you left off. The hops are dropped when you connect to a different radio. + ### What the User Sees A map with a polyline showing the route from your node through repeater hops to the target: - **Green circles**: Hops with known GPS coordinates diff --git a/documentation/notifications.md b/documentation/notifications.md index 0f08a095..535570c3 100644 --- a/documentation/notifications.md +++ b/documentation/notifications.md @@ -42,7 +42,7 @@ Message notifications can be answered without opening the app, from the notifica - **Reply** sends through the connected radio exactly like the chat screen: same length limits, SMAZ and Cyr2Lat handling, and retries. Your reply is then added to the notification. - **Replies over the message limit** are split at word boundaries into up to 3 messages. Longer replies are not sent; a "Reply not sent" notification asks you to open the app. - **Mark as read** clears the unread count on the phone only. MeshCore has no read receipts, so nothing is sent over the mesh. -- **Mute channel** (phone and watch) mutes that channel, the same as the bell icon in the channel chat. +- **Mute channel** (phone and watch) sets that channel to **Muted**, the same as choosing Muted from the bell icon in the channel chat. - If the radio is disconnected, the conversation is no longer on the radio, the radio reports a send error, or the app isn't running, a "Reply not sent" notification explains why. The reply is not queued. If a split reply fails partway, earlier parts may already have been sent. - Replies are sent as typed; composer translation is not applied. @@ -52,6 +52,14 @@ iOS notifications do not have reply actions yet. MeshCore Open works in Android Auto as a notification-based messaging app. There is no MeshCore screen in the car; Android Auto provides the interface. +Android Auto support is off by default and is compiled in only when the build passes the `androidAuto` Gradle property: + +```bash +flutter build apk --release --android-project-arg=androidAuto=true +``` + +The flag merges `android/app/src/androidAuto/` (the `com.google.android.gms.car.application` manifest entry and `automotive_app_desc.xml`) into the app. Without it, Android Auto does not list the app. Notification replies from the shade and watches work either way. + - New direct and channel messages appear on the car display and can be read aloud. - Reply by voice or with a suggested reply; replies follow the rules above (splitting, failure notifications, no translation). - Android Auto shows **Reply** and **Mark as read**. **Mute channel** is marked as a mute action, but Android Auto only documents reply and mark-as-read for messaging apps, so mute may not appear in the car; use the phone, a watch, or the bell icon. @@ -99,15 +107,24 @@ Access via **App Settings → Notifications**: | Channel Message Notifications | On | Channel alerts (greyed out if master is off) | | Advertisement Notifications | On | New node alerts (greyed out if master is off) | -### Per-Channel Muting +### Per-Channel Notification Modes -Mute or unmute a channel from any of these places. Muted channels do not generate OS notifications. +Each channel supports three notification modes: -- The bell icon in the channel chat app bar -- Long-press a channel in the channels list → "Mute channel" / "Unmute channel" -- **Mute channel** on a channel notification (Android) +| Mode | Icon | Behavior | +|---|---|---| +| **All messages** | 🔔 | Receive notifications for every message | +| **Mentions only** | 🔔! | Only notify when a message mentions your name (see below) | +| **Muted** | 🔕 | No notifications | -There is no per-contact muting. +Set the mode from: + +- The notifications icon in the channel chat app bar (tap to open the mode picker) +- Long-press a channel in the channels list → **Notification settings** → select mode + +The Android **Mute channel** notification action sets the channel to **Muted**; it cannot choose another mode. + +A message mentions you if it contains `@[yourname]` or `@yourname`, case-insensitively. The plain `@yourname` form must stand alone as a word, so `@bobby` does not mention `bob` and `x@bob.com` is not a mention; names with spaces must be written in full. Detection (`MeshCoreConnector.textMentionsName`) runs on the original text, before any automatic translation. ## Rate Limiting diff --git a/documentation/settings.md b/documentation/settings.md index 04fbe3ef..5ead1994 100644 --- a/documentation/settings.md +++ b/documentation/settings.md @@ -158,6 +158,20 @@ Not shown on web. Controls on-device message translation powered by a locally-do The auto-translate and composer toggles are disabled until **Enable translation** is on. +### IPFS Provider Configuration + +Open **App Settings → IPFS provider configuration** to configure IPFS uploads and previews: + +- **Public IPFS gateway**: Select Pinata, Filebase, a custom gateway, or deactivate it. This gateway lets the app load bare IPFS content IDs in image links. +- **Upload provider**: Select Pinata, Filebase, a custom provider, or deactivate uploads. Presets fill in the provider’s upload endpoint and upload gateway; custom setups can edit both. +- **API key**: Enter the credential required by the selected provider. The value is masked in the settings dialog. Pinata and Filebase presets require provider credentials. + +For a self-hosted Kubo node, choose **Custom (Kubo)** and configure its RPC upload endpoint and HTTP gateway. The preset defaults use `http://127.0.0.1:5001/api/v0/add` and `http://127.0.0.1:8080/ipfs/`; replace these with addresses reachable from the device running MeshCore Open. Do not expose Kubo’s unauthenticated RPC API to the public internet. + +When an **upload gateway** is configured, uploaded content is added to the draft as an HTTP(S) gateway URL in the form `http://gateway/ipfs/CID`. If it is blank, the app uses `ipfs://CID`. The public gateway setting is separate and is used to retrieve bare IPFS content IDs in incoming links. + +Save the settings before sharing. The upload action is shown in the chat composer only when an upload endpoint is configured. Provider accounts, credentials, limits, and terms are managed by the provider, not MeshCore Open. See [sharing images via IPFS](additional-features.md#share-an-image-via-ipfs) for the chat workflow. + ### Image Messages Image message controls live in App Settings → Messaging. Turn on **Enable image messages** first; **Process images automatically** and the image model download/cancel/removal controls then appear. Automatic processing reconstructs every image as it arrives and uses about 2 GB of memory for a second each time; leave it off to reconstruct with a tap. See [Image Messages](image-messages.md) for firmware, native-runtime, storage, and memory requirements. diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 03b03944..0784a1ed 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -38,7 +38,8 @@ import '../services/image_codec_service.dart'; import '../services/received_image_store.dart'; import '../services/message_retry_service.dart'; import '../services/path_history_service.dart'; -import '../services/app_settings_service.dart'; +import '../services/app_settings_service.dart' + show AppSettingsService, ChannelNotificationMode; import '../services/background_service.dart'; import '../services/timeout_prediction_service.dart'; import '../services/translation_service.dart'; @@ -66,6 +67,7 @@ import 'meshcore_uuids.dart'; import 'meshcore_protocol.dart'; import 'pending_command_replies.dart'; import 'raw_packet.dart'; +import '../utils/coalesced_writes.dart'; class DirectRepeater { static const int maxAgeMinutes = 30; // Max age for direct repeater info @@ -298,6 +300,22 @@ class MeshCoreConnector extends ChangeNotifier { Stopwatch? _airtimeBumpStopwatch; int _prevTotalAirSecs = 0; int? _batteryMillivolts; + // Thresholds (percent) that trigger a low-battery notification once per + // crossing, re-arming 5 points above the threshold after recharge. + static const List _lowBatteryThresholds = [25, 10]; + final Set _batteryAlertedThresholds = {}; + // Consecutive readings that newly crossed a threshold. Alerts need + // [_lowBatteryConfirmReadings] in a row so a single TX-load voltage sag + // doesn't notify. + int _lowBatteryReadingStreak = 0; + // Device key the posted low-battery notifications were scoped to, kept so + // they can still be cancelled after the session's identity is cleared. + String? _lowBatteryAlertDeviceKey; + static const int _lowBatteryConfirmReadings = 2; + // Readings below this are treated as "no battery sensor" (boards without + // one report 0 mV). Any single Li cell, including LiFePO4 (2600 mV empty), + // is protection-cut well above 2 V, so lower values are not real readings. + static const int _minPlausibleBatteryMillivolts = 2000; double? _selfLatitude; double? _selfLongitude; final List _directRepeaters = List.empty(growable: true); @@ -462,6 +480,9 @@ class MeshCoreConnector extends ChangeNotifier { BleDebugLogService? _bleDebugLogService; AppDebugLogService? _appDebugLogService; final ChannelMessageStore _channelMessageStore = ChannelMessageStore(); + // Per-frame persistence (channel history, conversations, contact lists) is + // batched here; see [CoalescedWrites]. + final CoalescedWrites _coalescedWrites = CoalescedWrites(); final MessageStore _messageStore = MessageStore(); final ChannelOrderStore _channelOrderStore = ChannelOrderStore(); final ChannelSettingsStore _channelSettingsStore = ChannelSettingsStore(); @@ -474,7 +495,7 @@ class MeshCoreConnector extends ChangeNotifier { List _cachedChannels = []; final Map _channelSmazEnabled = {}; final Map _channelCyr2LatEnabled = {}; - final Map _channelUrlImagesEnabled = {}; + final Map _channelUrlImagesEnabled = {}; final Map _channelCyr2LatProfileId = {}; final Map _channelRegions = {}; Region _defaultRegion = ''; @@ -484,7 +505,7 @@ class MeshCoreConnector extends ChangeNotifier { Uint8List? _defaultFloodScopeKey; final Map _contactSmazEnabled = {}; final Map _contactCyr2LatEnabled = {}; - final Map _contactUrlImagesEnabled = {}; + final Map _contactUrlImagesEnabled = {}; final Map _contactCyr2LatProfileId = {}; final Set _knownContactKeys = {}; final Map _contactUnreadCount = {}; @@ -667,6 +688,16 @@ class MeshCoreConnector extends ChangeNotifier { bool? get autoAddSensors => _autoAddSensors; bool? get autoAddOverwriteOldest => _overwriteOldest; + /// Whether the radio stores adverts of [type] by itself, so a removed + /// contact of that type returns the next time it advertises. + bool autoAddsContactType(int type) => switch (type) { + advTypeChat => _autoAddUsers, + advTypeRepeater => _autoAddRepeaters, + advTypeRoom => _autoAddRoomServers, + advTypeSensor => _autoAddSensors, + _ => false, + }; + /// autoadd_max_hops from GET_AUTOADD_CONFIG (0 = no limit), null when the /// firmware did not report it (pre-v1.13). int? get autoAddMaxHops => _autoAddMaxHops; @@ -681,6 +712,9 @@ class MeshCoreConnector extends ChangeNotifier { /// from ver code 8. bool get supportsNodeDiscover => (_firmwareVerCode ?? 0) >= 8; + /// CMD_SET_PATH_HASH_MODE exists from ver code 10 (v1.14.0). + bool get supportsPathHashMode => (_firmwareVerCode ?? 0) >= 10; + /// CMD_GET/SET_DEFAULT_FLOOD_SCOPE exist from ver code 11 (v1.15.0). bool get supportsDefaultFloodScope => (_firmwareVerCode ?? 0) >= 11; @@ -958,9 +992,40 @@ class MeshCoreConnector extends ChangeNotifier { Future _saveChannelMessages(int slot, List messages) { final id = _channelIdForSlot(slot); if (id == null) return Future.value(); + _coalescedWrites.cancel('channel:$id'); return _channelMessageStore.saveChannelMessages(id, messages); } + /// Queues a save of [slot]'s history. The write looks the channel up again + /// when it runs, so it persists whatever the history is by then and skips a + /// channel that was removed in the meantime. + void _scheduleChannelSave(int slot) { + final id = _channelIdForSlot(slot); + if (id == null) return; + _coalescedWrites.schedule('channel:$id', () { + final currentSlot = _slotForChannelId(id); + final messages = currentSlot == null + ? null + : _channelMessages[_canonicalSlot(currentSlot)]; + if (messages == null) return Future.value(); + return _channelMessageStore.saveChannelMessages(id, messages); + }); + } + + /// Queues a save of the conversation with [contactKeyHex]; skipped when the + /// conversation is gone by the time it runs. + void _scheduleConversationSave(String contactKeyHex) { + _coalescedWrites.schedule('conversation:$contactKeyHex', () { + final messages = _conversations[contactKeyHex]; + if (messages == null) return Future.value(); + return _messageStore.saveMessages(contactKeyHex, messages); + }); + } + + /// Runs queued persistence now. Called before the app is backgrounded and + /// whenever the stores are about to switch to another radio. + Future flushPendingWrites() => _coalescedWrites.flush(); + int getUnreadCountForContact(Contact contact) { if (contact.type == advTypeRepeater) return 0; return getUnreadCountForContactKey(contact.publicKeyHex); @@ -1029,13 +1094,25 @@ class MeshCoreConnector extends ChangeNotifier { return _contactSmazEnabled[contactKeyHex] ?? false; } + bool _lastShowLinkImagesByDefault = false; + + void _onAppSettingsChanged() { + final showByDefault = _showLinkImagesByDefault; + if (showByDefault == _lastShowLinkImagesByDefault) return; + _lastShowLinkImagesByDefault = showByDefault; + notifyListeners(); + } + + bool get _showLinkImagesByDefault => + _appSettingsService?.settings.showLinkImagesByDefault ?? false; + bool isChannelUrlImagesEnabled(int channelIndex) { - return _channelUrlImagesEnabled[channelIndex] ?? false; + return _channelUrlImagesEnabled[channelIndex] ?? _showLinkImagesByDefault; } bool isContactUrlImagesEnabled(String contactKeyHex) { _ensureContactUrlImagesSettingLoaded(contactKeyHex); - return _contactUrlImagesEnabled[contactKeyHex] ?? false; + return _contactUrlImagesEnabled[contactKeyHex] ?? _showLinkImagesByDefault; } /// True when the channel has its own (real) region assigned. @@ -1202,6 +1279,17 @@ class MeshCoreConnector extends ChangeNotifier { notifyListeners(); } + /// Queues a save of the channel list, which carries the unread counts that + /// change on every received channel message. + void _scheduleChannelListSave() { + _coalescedWrites.schedule( + 'channels', + () => _channelStore.saveChannels( + _channels.isNotEmpty ? _channels : _cachedChannels, + ), + ); + } + void setChannelUnreadCount(int channelIndex, int count) { final channel = _findChannelByIndex(channelIndex); if (channel != null) { @@ -1209,11 +1297,7 @@ class MeshCoreConnector extends ChangeNotifier { channel.unreadCount = count; final total = _cachedChannelsUnreadTotal + (count - previousCount); _cachedChannelsUnreadTotal = total < 0 ? 0 : total; - unawaited( - _channelStore.saveChannels( - _channels.isNotEmpty ? _channels : _cachedChannels, - ), - ); + _scheduleChannelListSave(); notifyListeners(); } } @@ -1229,11 +1313,7 @@ class MeshCoreConnector extends ChangeNotifier { 'Channel ${channel.name.isNotEmpty ? channel.name : channelIndex} marked as read (was $previousCount unread)', tag: 'Unread', ); - unawaited( - _channelStore.saveChannels( - _channels.isNotEmpty ? _channels : _cachedChannels, - ), - ); + _scheduleChannelListSave(); _notificationService.clearChannelNotification( channelIndex, getTotalUnreadCount(), @@ -1246,8 +1326,9 @@ class MeshCoreConnector extends ChangeNotifier { /// (notification shade, watch, or Android Auto). Future handleNotificationReply(NotificationReply reply) async { if (reply.action == NotificationReplyAction.mute) { - await _appSettingsService?.muteChannel( + await _appSettingsService?.setChannelNotificationMode( _channelDisplayName(reply.channelIndex!), + ChannelNotificationMode.muted, ); await _notificationService.clearChannelNotification( reply.channelIndex!, @@ -1492,6 +1573,9 @@ class MeshCoreConnector extends ChangeNotifier { /// Load persisted channel messages for a specific channel Future _loadChannelMessages(int channelIndex) async { + // The load replaces the in-memory history, so queued writes of it must + // reach storage (whose cache updates synchronously) first. + unawaited(_coalescedWrites.flush()); final channelId = _slotChannelIds[channelIndex]; final allMessages = channelId == null ? [] @@ -1590,6 +1674,8 @@ class MeshCoreConnector extends ChangeNotifier { _retryService = retryService; _pathHistoryService = pathHistoryService; _appSettingsService = appSettingsService; + _lastShowLinkImagesByDefault = _showLinkImagesByDefault; + appSettingsService?.addListener(_onAppSettingsChanged); _translationService = translationService; _imageCodecService = imageCodecService; _imageTransport = imageTransport; @@ -3794,6 +3880,9 @@ class MeshCoreConnector extends ChangeNotifier { if (pendingAck != null) { _pendingGenericAckQueue.remove(pendingAck); } + if (_activeTransport == MeshCoreTransportType.tcp) { + unawaited(disconnect(manual: false)); + } rethrow; } @@ -4356,7 +4445,7 @@ class MeshCoreConnector extends ChangeNotifier { _pathOpLock = completer.future; await prev; try { - if (!isConnected) return; + if (!isConnected || !_isKnownContact(contact)) return; final width = pathHashWidth ?? @@ -4399,6 +4488,13 @@ class MeshCoreConnector extends ChangeNotifier { } } + /// Whether [contact] is still in the radio's contact list. The firmware's + /// CMD_ADD_UPDATE_CONTACT adds unknown keys, so path/flag writes for a + /// removed contact (e.g. a repeater screen still open after its old key was + /// deleted) would re-create it on the radio. + bool _isKnownContact(Contact contact) => + _contacts.any((c) => c.publicKeyHex == contact.publicKeyHex); + /// The advert timestamp the firmware holds for [contact] (Contact.lastSeen /// is parsed from that field); the stored copy is freshest. DateTime _deviceLastAdvert(Contact contact) { @@ -4415,7 +4511,7 @@ class MeshCoreConnector extends ChangeNotifier { bool? teleLoc, bool? teleEnv, }) async { - if (!isConnected) return; + if (!isConnected || !_isKnownContact(contact)) return; final latestContact = await _fetchContactSnapshotFromDevice(contact.publicKey) ?? contact; int updatedFlags = isFavorite != null @@ -5034,13 +5130,26 @@ class MeshCoreConnector extends ChangeNotifier { }) async { if (!isConnected) return; + // Only drop the contact locally once the radio confirms; otherwise the + // next contact sync restores it. ERR means the radio does not have it. + try { + await sendFrame( + buildRemoveContactFrame(contact.publicKey), + waitForGenericAck: true, + ); + } on FirmwareCommandException catch (e) { + _appDebugLogService?.warn( + 'Radio has no contact ${contact.publicKeyHex.substring(0, 8)} ' + '(error ${e.errCode}); removing it locally', + tag: 'Connector', + ); + } + _handleDiscovery( contact, contact.rawPacket ?? Uint8List(0), noNotify: true, ); - - await sendFrame(buildRemoveContactFrame(contact.publicKey)); _contactsStorageFull = false; _contacts.removeWhere((c) => c.publicKeyHex == contact.publicKeyHex); _knownContactKeys.remove(contact.publicKeyHex); @@ -5069,7 +5178,7 @@ class MeshCoreConnector extends ChangeNotifier { ), ); } - unawaited(_persistDiscoveredContacts()); + _scheduleDiscoveredContactsPersist(); notifyListeners(); } @@ -5078,7 +5187,7 @@ class MeshCoreConnector extends ChangeNotifier { _discoveredContacts.removeWhere( (c) => c.publicKeyHex == contact.publicKeyHex, ); - unawaited(_persistDiscoveredContacts()); + _scheduleDiscoveredContactsPersist(); notifyListeners(); } @@ -5204,7 +5313,7 @@ class MeshCoreConnector extends ChangeNotifier { ), ); notifyListeners(); - unawaited(_persistDiscoveredContacts()); + _scheduleDiscoveredContactsPersist(); return true; } @@ -5649,6 +5758,9 @@ class MeshCoreConnector extends ChangeNotifier { '$unconfirmed', ); } + // Queued channel writes find their channel by slot; land them before + // the map moves, or a channel whose slot changed would never be saved. + unawaited(_coalescedWrites.flush()); _slotChannelIds ..clear() ..addAll(next); @@ -5774,6 +5886,7 @@ class MeshCoreConnector extends ChangeNotifier { ); await _loadChannelOrder(); final saved = await _channelStore.loadSlotChannelIds(); + unawaited(_coalescedWrites.flush()); _slotChannelIds ..clear() ..addAll(saved); @@ -5846,22 +5959,32 @@ class MeshCoreConnector extends ChangeNotifier { _findChannelByIndex(index)?.storageId ?? _slotChannelIds[index]; // Delete by setting empty name and zero PSK await sendFrame(buildSetChannelFrame(index, '', Uint8List(16))); - // Another slot holding the same PSK keeps the shared history. - final stillHeld = _channels.any( - (channel) => channel.index != index && channel.storageId == channelId, - ); - if (channelId != null && !stillHeld) { - await _clearChannelStorage(channelId); - } + // A twin slot with the same PSK keeps this history, so queued writes of + // it land before the list is dropped; a full delete clears them below. + unawaited(_coalescedWrites.flush()); _channelMessages.remove(index); _processedChannelReactions.remove(index); - // Refresh channels after deleting - await getChannels(force: true); + try { + // Refresh before clearing history so messages from an in-flight queue + // sync cannot recreate the channel's stored history after it is deleted. + await getChannels(force: true); + } finally { + // Another slot holding the same PSK keeps the shared history. The + // deleted slot is skipped: a failed or partial refresh can leave it in + // the map. + final stillHeld = _slotChannelIds.entries.any( + (entry) => entry.key != index && entry.value == channelId, + ); + if (channelId != null && !stillHeld) { + await _clearChannelStorage(channelId); + } + } } /// Removes everything persisted for [channelId]: messages, settings, /// region, images and its place in the channel order. Future _clearChannelStorage(String channelId) async { + _coalescedWrites.cancel('channel:$channelId'); await _channelMessageStore.clearChannelMessages(channelId); await _channelSettingsStore.clearChannel(channelId); await _channelRegionStore.clearRegion(channelId); @@ -6253,6 +6376,7 @@ class MeshCoreConnector extends ChangeNotifier { return; } + unawaited(_coalescedWrites.flush()); //set all the stores' public key so they can load the correct data _channelMessageStore.setPublicKeyHex = selfPublicKeyHex; _messageStore.setPublicKeyHex = selfPublicKeyHex; @@ -6471,6 +6595,7 @@ class MeshCoreConnector extends ChangeNotifier { _batteryMillivolts = reader.readUInt16LE(); _storageUsedKb = reader.readUInt32LE(); _storageTotalKb = reader.readUInt32LE(); + _checkLowBatteryThresholds(); final volts = (_batteryMillivolts! / 1000.0).toStringAsFixed(2); _appDebugLogService?.info( 'Pulled battery: $volts V ($_batteryMillivolts mV)', @@ -6485,6 +6610,64 @@ class MeshCoreConnector extends ChangeNotifier { } } + void _checkLowBatteryThresholds() { + final millivolts = _batteryMillivolts; + if (millivolts == null || millivolts < _minPlausibleBatteryMillivolts) { + return; + } + // Until the device identity (and so its saved chemistry) is known, the + // percentage falls back to NMC and can read low for e.g. LiFePO4 packs. + // Skip evaluation; the next battery poll re-checks once identity is set. + if (batteryDeviceKey == null || _appSettingsService == null) return; + final percent = batteryPercent; + if (percent == null) return; + + // Only the lowest newly crossed threshold notifies; higher ones crossed + // in the same reading are marked as alerted silently. + final newlyCrossed = []; + for (final threshold in _lowBatteryThresholds) { + if (percent <= threshold && + !_batteryAlertedThresholds.contains(threshold)) { + newlyCrossed.add(threshold); + } else if (percent > threshold + 5 && + _batteryAlertedThresholds.contains(threshold)) { + // Re-arm once the battery recovers 5 points above the threshold, + // so a recharge + discharge cycle alerts again without flapping. + _batteryAlertedThresholds.remove(threshold); + final alertDeviceKey = _lowBatteryAlertDeviceKey; + if (alertDeviceKey != null) { + unawaited( + _notificationService.clearLowBatteryNotifications(alertDeviceKey, [ + threshold, + ]), + ); + } + } + } + if (newlyCrossed.isEmpty) { + _lowBatteryReadingStreak = 0; + return; + } + // Debounce: wait for consecutive low readings before alerting. + if (++_lowBatteryReadingStreak < _lowBatteryConfirmReadings) return; + _lowBatteryReadingStreak = 0; + _batteryAlertedThresholds.addAll(newlyCrossed); + final deviceKey = batteryDeviceKey!; + _lowBatteryAlertDeviceKey = deviceKey; + final lowestNewlyCrossed = newlyCrossed.reduce((a, b) => a < b ? a : b); + if (!(_appSettingsService?.settings.notificationsEnabled ?? false)) { + return; + } + unawaited( + _notificationService.showLowBatteryNotification( + deviceKey: deviceKey, + deviceName: deviceDisplayName, + batteryPercent: percent, + threshold: lowestNewlyCrossed, + ), + ); + } + void _checkManualAddContacts() async { // If manual add contacts is enabled, set auto add config and other params. // and disable it after @@ -6820,14 +7003,27 @@ class MeshCoreConnector extends ChangeNotifier { } } + /// Queues a save of the contact list; adverts and contact replies arrive + /// many times a second on a busy mesh. Future _persistContacts() async { - await _contactStore.saveContacts(_contacts); + _coalescedWrites.schedule( + 'contacts', + () => _contactStore.saveContacts(_contacts), + ); } Future _persistDiscoveredContacts() async { + _coalescedWrites.cancel('discovered'); await _discoveryContactStore.saveContacts(_discoveredContacts); } + void _scheduleDiscoveredContactsPersist() { + _coalescedWrites.schedule( + 'discovered', + () => _discoveryContactStore.saveContacts(_discoveredContacts), + ); + } + int _latestContactLastmod() { if (_contacts.isEmpty) return 0; var latest = 0; @@ -7201,7 +7397,7 @@ class MeshCoreConnector extends ChangeNotifier { void _ensureContactUrlImagesSettingLoaded(String contactKeyHex) { if (_contactUrlImagesEnabled.containsKey(contactKeyHex)) return; _contactSettingsStore.loadUrlImagesEnabled(contactKeyHex).then((enabled) { - if (_contactUrlImagesEnabled[contactKeyHex] == enabled) return; + if (_contactUrlImagesEnabled.containsKey(contactKeyHex)) return; _contactUrlImagesEnabled[contactKeyHex] = enabled; notifyListeners(); }); @@ -7353,7 +7549,12 @@ class MeshCoreConnector extends ChangeNotifier { } final label = channelName ?? _channelDisplayName(channelIndex); - if (_appSettingsService!.isChannelMuted(label)) return; + final notificationMode = _appSettingsService!.getChannelNotificationMode( + label, + ); + + // Check if channel is muted + if (notificationMode == ChannelNotificationMode.muted) return; // Reuse translation result only if completed and non-empty; else use original text final resolvedText = @@ -7362,6 +7563,14 @@ class MeshCoreConnector extends ChangeNotifier { translationResult.translatedText.trim().isNotEmpty) ? translationResult.translatedText.trim() : message.text.trim(); + + // Mentions are matched on the untranslated text. + if (notificationMode == ChannelNotificationMode.mentionsOnly) { + if (!textMentionsName(message.originalText ?? message.text, _selfName)) { + return; + } + } + unawaited(() async { await _notificationService.showChannelMessageNotification( channelName: label, @@ -7374,6 +7583,22 @@ class MeshCoreConnector extends ChangeNotifier { }()); } + /// Whether [text] mentions [name], case-insensitively, as either + /// `@[name]` (the reply/mention prefix the app sends) or a plain `@name`. + /// The plain form needs a word boundary on both sides, so `@bobby` does + /// not mention `bob` and `x@bob.com` is not a mention. Names containing + /// spaces must be written out in full. + @visibleForTesting + static bool textMentionsName(String text, String? name) { + if (name == null || name.isEmpty) return false; + final escaped = RegExp.escape(name); + return RegExp( + '@\\[$escaped\\]|(? 0) messages.removeRange(0, overflow); } - // Save to persistent storage - _saveChannelMessages(channelIndex, messages); + _scheduleChannelSave(channelIndex); return isNew; } @@ -8522,6 +8747,7 @@ class MeshCoreConnector extends ChangeNotifier { } void _handleDisconnection() { + unawaited(_coalescedWrites.flush()); _resetLinkSessionState(); _notifySubscription?.cancel(); @@ -8568,6 +8794,18 @@ class MeshCoreConnector extends ChangeNotifier { _hasReceivedDeviceInfo = false; _batteryMillivolts = null; _batteryRequested = false; + final alertDeviceKey = _lowBatteryAlertDeviceKey; + if (alertDeviceKey != null && _batteryAlertedThresholds.isNotEmpty) { + unawaited( + _notificationService.clearLowBatteryNotifications( + alertDeviceKey, + _batteryAlertedThresholds.toList(), + ), + ); + } + _batteryAlertedThresholds.clear(); + _lowBatteryAlertDeviceKey = null; + _lowBatteryReadingStreak = 0; _pathHashByteWidth = 1; _maxContacts = _defaultMaxContacts; _maxChannels = _defaultMaxChannels; @@ -8581,6 +8819,9 @@ class MeshCoreConnector extends ChangeNotifier { /// Drops the conversation and channel history held in memory, so a /// different radio never shows or persists another radio's messages. void _clearSessionMessageState() { + // Writes start synchronously, so they still read this radio's history and + // store keys before both change below. + unawaited(_coalescedWrites.flush()); _conversations.clear(); _loadedConversationKeys.clear(); _channelMessages.clear(); @@ -8714,6 +8955,7 @@ class MeshCoreConnector extends ChangeNotifier { @override void dispose() { _disposed = true; + _appSettingsService?.removeListener(_onAppSettingsChanged); _scanSubscription?.cancel(); _isScanningSubscription?.cancel(); _connectionSubscription?.cancel(); @@ -8722,6 +8964,7 @@ class MeshCoreConnector extends ChangeNotifier { _notificationReplySubscription?.cancel(); _notificationService.releaseReplyPort(); _notifyListenersTimer?.cancel(); + unawaited(_coalescedWrites.flush()); _reconnectTimer?.cancel(); _batteryPollTimer?.cancel(); _gpsLocationPollTimer?.cancel(); @@ -9203,7 +9446,7 @@ class MeshCoreConnector extends ChangeNotifier { isActive: addActive, ); notifyListeners(); - unawaited(_persistDiscoveredContacts()); + _scheduleDiscoveredContactsPersist(); return; } @@ -9230,7 +9473,7 @@ class MeshCoreConnector extends ChangeNotifier { } _discoveredContacts.add(disContact); - unawaited(_persistDiscoveredContacts()); + _scheduleDiscoveredContactsPersist(); // Show notification for new contact (advertisement) if (_appSettingsService != null && !noNotify) { @@ -9260,7 +9503,7 @@ class MeshCoreConnector extends ChangeNotifier { void removeAllDiscoveredContacts() { _discoveredContacts.clear(); - unawaited(_persistDiscoveredContacts()); + _scheduleDiscoveredContactsPersist(); notifyListeners(); } diff --git a/lib/connector/meshcore_protocol.dart b/lib/connector/meshcore_protocol.dart index 126110ad..22476f63 100644 --- a/lib/connector/meshcore_protocol.dart +++ b/lib/connector/meshcore_protocol.dart @@ -497,8 +497,16 @@ String ackHashToHex(int ackHash) { } // Helper to convert public key to hex string +const String _hexDigits = '0123456789abcdef'; + String pubKeyToHex(Uint8List pubKey) { - return pubKey.map((b) => b.toRadixString(16).padLeft(2, '0')).join(); + final codes = Uint8List(pubKey.length * 2); + for (var i = 0; i < pubKey.length; i++) { + final b = pubKey[i]; + codes[i * 2] = _hexDigits.codeUnitAt(b >> 4); + codes[i * 2 + 1] = _hexDigits.codeUnitAt(b & 0x0F); + } + return String.fromCharCodes(codes); } // Helper to convert hex string to public key diff --git a/lib/connector/pending_command_replies.dart b/lib/connector/pending_command_replies.dart index a0dc9b5d..094846e2 100644 --- a/lib/connector/pending_command_replies.dart +++ b/lib/connector/pending_command_replies.dart @@ -5,6 +5,16 @@ import 'package:flutter/foundation.dart'; import '../services/image_chunk_transport.dart' show cmdSendChannelData; import 'meshcore_protocol.dart'; +/// RESP_CODE_ERR received for a command that was waiting for its reply. +class FirmwareCommandException implements Exception { + final int errCode; + + const FirmwareCommandException(this.errCode); + + @override + String toString() => 'Exception: Command failed with error code $errCode'; +} + /// A command waiting for its reply from the companion firmware. class PendingCommandReply { final int commandCode; @@ -203,9 +213,7 @@ class PendingCommandReplies { if (_queue.isEmpty) return null; final pending = _queue.removeAt(0); if (pending.isTombstone) return null; - pending.completer?.completeError( - Exception('Command failed with error code $errCode'), - ); + pending.completer?.completeError(FirmwareCommandException(errCode)); return pending; } diff --git a/lib/helpers/ipfs_link_attach_flow.dart b/lib/helpers/ipfs_link_attach_flow.dart new file mode 100644 index 00000000..e1cb6530 --- /dev/null +++ b/lib/helpers/ipfs_link_attach_flow.dart @@ -0,0 +1,147 @@ +import 'dart:convert'; + +import 'package:file_selector/file_selector.dart' as file_selector; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../l10n/app_localizations.dart'; +import '../l10n/l10n.dart'; +import '../services/app_settings_service.dart'; +import 'ipfs_upload_helper.dart'; +import 'snack_bar_builder.dart'; + +/// Shared "send image via IPFS" flow for the direct-message and channel chat +/// screens: picks a file, uploads it with the configured IPFS settings and +/// puts the resulting link at the start of the composer draft. +/// +/// [maxBytes] is the screen's outbound byte limit and [encodeOutbound] turns +/// draft text into exactly what the send path measures (including any reply +/// prefix), so the limit is checked against that form. The draft is never +/// shortened: if the link won't fit, nothing is uploaded and the user is told +/// to shorten the message. +Future attachIpfsLinkToDraft({ + required BuildContext context, + required TextEditingController controller, + required FocusNode focusNode, + required int maxBytes, + required String Function(String text) encodeOutbound, +}) async { + final l10n = context.l10n; + final settings = context.read().settings; + if (settings.uploadIpfsEndpoint.trim().isEmpty) { + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadNotConfigured), + ); + return; + } + + String draftWithLink(String messageUrl) => composeIpfsLinkDraft( + messageUrl: messageUrl, + existingText: controller.text.trim(), + ); + bool fits(String draft) => ipfsLinkDraftFits( + draft, + maxBytes: maxBytes, + encodeOutbound: encodeOutbound, + ); + + final sampleLink = IpfsUploadHelper.linkForCid( + uploadGateway: settings.uploadIpfsGateway, + cid: IpfsUploadHelper.sampleCid, + ); + if (!fits(draftWithLink(sampleLink))) { + showDismissibleSnackBar(context, content: Text(l10n.chat_ipfsLinkNoRoom)); + return; + } + + void showFailure(Object error) { + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(ipfsUploadErrorText(l10n, error)), + ); + } + + final String messageUrl; + try { + final file = await file_selector.openFile(); + if (file == null || !context.mounted) return; + final bytes = await file.readAsBytes(); + if (!context.mounted) return; + if (bytes.isEmpty) { + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsSelectedFileEmpty), + ); + return; + } + messageUrl = await IpfsUploadHelper.uploadImageWithSettings( + settings: settings, + bytes: bytes, + fileName: file.name, + mimeType: IpfsUploadHelper.mimeTypeForFileName(file.name), + ); + } on Exception catch (error) { + showFailure(error); + return; + } catch (error, stackTrace) { + FlutterError.reportError( + FlutterErrorDetails( + exception: error, + stack: stackTrace, + library: 'ipfs link attach', + ), + ); + showFailure(error); + return; + } + if (!context.mounted) return; + + final messageText = draftWithLink(messageUrl); + controller.value = TextEditingValue( + text: messageText, + selection: TextSelection.collapsed(offset: messageText.length), + ); + focusNode.requestFocus(); + if (!fits(messageText)) { + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsLinkOverLimit), + ); + } +} + +/// The localized snackbar text for an upload [error]: config problems get a +/// specific message, anything else a generic one with technical details. +@visibleForTesting +String ipfsUploadErrorText(AppLocalizations l10n, Object error) { + if (error is IpfsUploadConfigException) { + return switch (error.reason) { + IpfsUploadConfigError.emptyEndpoint => l10n.chat_ipfsUploadNotConfigured, + IpfsUploadConfigError.invalidEndpoint => l10n.chat_ipfsEndpointInvalid, + IpfsUploadConfigError.pinataTokenMissing => + l10n.chat_ipfsPinataTokenMissing, + IpfsUploadConfigError.filebaseTokenMissing => + l10n.chat_ipfsFilebaseTokenMissing, + IpfsUploadConfigError.kuboPathInvalid => l10n.chat_ipfsKuboPathInvalid, + }; + } + final details = '$error'.replaceFirst(RegExp(r'^Exception: '), ''); + return l10n.chat_ipfsUploadFailed(details); +} + +/// Puts [messageUrl] in front of [existingText], leaving the text intact. +@visibleForTesting +String composeIpfsLinkDraft({ + required String messageUrl, + required String existingText, +}) => existingText.isEmpty ? '$messageUrl ' : '$messageUrl\n$existingText'; + +/// Whether [draft], encoded the way the send path encodes it, fits [maxBytes]. +@visibleForTesting +bool ipfsLinkDraftFits( + String draft, { + required int maxBytes, + required String Function(String text) encodeOutbound, +}) => utf8.encode(encodeOutbound(draft.trim())).length <= maxBytes; diff --git a/lib/helpers/ipfs_upload_helper.dart b/lib/helpers/ipfs_upload_helper.dart new file mode 100644 index 00000000..7f6e36e1 --- /dev/null +++ b/lib/helpers/ipfs_upload_helper.dart @@ -0,0 +1,228 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; + +import '../models/app_settings.dart'; + +/// Why the IPFS upload settings can't be used. +enum IpfsUploadConfigError { + emptyEndpoint, + invalidEndpoint, + pinataTokenMissing, + filebaseTokenMissing, + kuboPathInvalid, +} + +/// Thrown when the IPFS upload settings can't be used, before or instead of +/// a network failure. The UI maps [reason] to a localized message. +class IpfsUploadConfigException implements Exception { + const IpfsUploadConfigException(this.reason); + + final IpfsUploadConfigError reason; + + @override + String toString() => 'IpfsUploadConfigException(${reason.name})'; +} + +class IpfsUploadHelper { + @visibleForTesting + static http.Client? httpClient; + + static final _kuboAddPath = RegExp(r'/api/v0/add/?$'); + + /// A CIDv1 (base32, sha2-256) as long as the CID of every upload, used to + /// size the link before uploading. + static const sampleCid = + 'bafkreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku'; + + static String linkForCid({ + required String uploadGateway, + required String cid, + }) { + final gateway = normalizeIpfsGateway(uploadGateway); + return gateway.isEmpty ? 'ipfs://$cid' : '$gateway$cid'; + } + + static String mimeTypeForFileName(String fileName) { + switch (fileName.toLowerCase().split('.').last) { + case 'jpg': + case 'jpeg': + return 'image/jpeg'; + case 'png': + return 'image/png'; + case 'gif': + return 'image/gif'; + case 'webp': + return 'image/webp'; + case 'heic': + return 'image/heic'; + default: + return 'application/octet-stream'; + } + } + + static Future uploadImageWithSettings({ + required AppSettings settings, + required Uint8List bytes, + required String fileName, + required String mimeType, + }) { + return uploadImage( + bytes: bytes, + fileName: fileName, + mimeType: mimeType, + uploadEndpoint: settings.uploadIpfsEndpoint, + uploadApiKey: settings.uploadIpfsApiKey, + uploadGateway: settings.uploadIpfsGateway, + ); + } + + static Future uploadImage({ + required Uint8List bytes, + required String fileName, + required String mimeType, + required String uploadEndpoint, + required String uploadApiKey, + String uploadGateway = '', + }) async { + final endpoint = uploadEndpoint.trim(); + if (endpoint.isEmpty) { + throw const IpfsUploadConfigException( + IpfsUploadConfigError.emptyEndpoint, + ); + } + + final endpointUri = Uri.tryParse(endpoint); + if (endpointUri == null || + !(endpointUri.isScheme('http') || endpointUri.isScheme('https')) || + endpointUri.host.isEmpty) { + throw const IpfsUploadConfigException( + IpfsUploadConfigError.invalidEndpoint, + ); + } + + final token = uploadApiKey.trim(); + final endpointHost = endpointUri.host.toLowerCase(); + final isPinata = + endpointHost.contains('pinata') || + endpoint.toLowerCase().contains('pinfiletoipfs'); + final isFilebase = endpointHost.contains('filebase'); + final isKubo = !isPinata && !isFilebase; + final safeFileName = _sanitizeUploadFileName(fileName); + if (isPinata && token.isEmpty) { + throw const IpfsUploadConfigException( + IpfsUploadConfigError.pinataTokenMissing, + ); + } + if (isFilebase && token.isEmpty) { + throw const IpfsUploadConfigException( + IpfsUploadConfigError.filebaseTokenMissing, + ); + } + if (isKubo && !_kuboAddPath.hasMatch(endpointUri.path)) { + throw const IpfsUploadConfigException( + IpfsUploadConfigError.kuboPathInvalid, + ); + } + + final uploadUri = isPinata + ? endpointUri + : endpointUri.replace( + queryParameters: { + ...endpointUri.queryParameters, + 'cid-version': '1', + if (isKubo) 'pin': 'true', + }, + ); + + final request = http.MultipartRequest('POST', uploadUri) + ..files.add( + http.MultipartFile.fromBytes('file', bytes, filename: safeFileName), + ); + if (token.isNotEmpty) { + request.headers['Authorization'] = 'Bearer $token'; + } + if (isPinata) { + request.fields['pinataOptions'] = jsonEncode({'cidVersion': 1}); + request.fields['pinataMetadata'] = jsonEncode({'name': safeFileName}); + } + + final client = httpClient; + final response = await (client == null + ? request.send() + : client.send(request)); + final body = await response.stream.bytesToString(); + if (response.statusCode < 200 || response.statusCode >= 300) { + throw Exception('IPFS upload failed (${response.statusCode}): $body'); + } + + final cid = _extractUploadCid(body, isPinata: isPinata); + if (cid == null || cid.isEmpty) { + throw Exception('IPFS upload did not return a CID.'); + } + + if (isKubo) { + await _copyKuboFileToMfs( + addUri: endpointUri, + cid: cid, + fileName: safeFileName, + authorization: token.isEmpty ? null : 'Bearer $token', + ); + } + + return linkForCid(uploadGateway: uploadGateway, cid: cid); + } + + static Future _copyKuboFileToMfs({ + required Uri addUri, + required String cid, + required String fileName, + required String? authorization, + }) async { + final mfsPath = '/meshcore_uploads/$cid-$fileName'; + final copyUri = addUri.replace( + path: addUri.path.replaceFirst(_kuboAddPath, '/api/v0/files/cp'), + query: + 'arg=${Uri.encodeQueryComponent('/ipfs/$cid')}' + '&arg=${Uri.encodeQueryComponent(mfsPath)}&parents=true', + ); + final headers = authorization == null + ? {} + : {'Authorization': authorization}; + final client = httpClient; + final response = await (client == null + ? http.post(copyUri, headers: headers) + : client.post(copyUri, headers: headers)); + final alreadyCopied = response.body.contains('already has entry'); + if ((response.statusCode < 200 || response.statusCode >= 300) && + !alreadyCopied) { + throw Exception( + 'Kubo MFS import failed (${response.statusCode}): ${response.body}', + ); + } + } + + static String _sanitizeUploadFileName(String name) { + final cleaned = name.replaceAll(RegExp(r'[<>:"/\\|?*]'), '_').trim(); + return cleaned.isEmpty ? 'shared-image' : cleaned; + } + + static String? _extractUploadCid(String body, {required bool isPinata}) { + final lines = const LineSplitter() + .convert(body) + .where((line) => line.trim().isNotEmpty) + .toList(); + for (final line in lines.reversed) { + try { + final decoded = jsonDecode(line); + if (decoded is! Map) continue; + final value = isPinata ? decoded['IpfsHash'] : decoded['Hash']; + if (value is String && value.isNotEmpty) return value; + } catch (_) { + continue; + } + } + return null; + } +} diff --git a/lib/helpers/marker_message.dart b/lib/helpers/marker_message.dart new file mode 100644 index 00000000..52f251c6 --- /dev/null +++ b/lib/helpers/marker_message.dart @@ -0,0 +1,30 @@ +import 'package:latlong2/latlong.dart'; + +class MarkerPayload { + final LatLng position; + final String label; + final String flags; + + MarkerPayload({ + required this.position, + required this.label, + required this.flags, + }); +} + +/// Parse a shared marker text message of the form +/// `m:,|