Merge pull request #1308 from OffbandMesh/feat/1289-link-router
feat(#1289, #1291): open meshcore:// share links in Offbandpull/1319/head
commit
092676cd42
@ -0,0 +1,69 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../models/channel.dart';
|
||||
import 'channel_slot_ui.dart';
|
||||
import 'snack_bar_builder.dart';
|
||||
|
||||
enum SharedChannelAdd { added, alreadyExists, cancelled, refused }
|
||||
|
||||
/// Asks the user to confirm adding a shared [channel], then writes it.
|
||||
///
|
||||
/// Every way a shared channel arrives goes through here: a scanned QR, a
|
||||
/// tapped link, a link handed over by the OS (#1289). The slot is chosen
|
||||
/// after the user confirms, never before: a channel sync during the dialog
|
||||
/// could otherwise leave it pointing at an occupied slot (#1021).
|
||||
///
|
||||
/// A refusal has already been explained to the user when this returns
|
||||
/// [SharedChannelAdd.refused], so the caller should not show anything over
|
||||
/// it.
|
||||
Future<SharedChannelAdd> confirmAndAddSharedChannel(
|
||||
BuildContext context,
|
||||
Channel channel,
|
||||
) async {
|
||||
final connector = context.read<MeshCoreConnector>();
|
||||
if (connector.channels.any((c) => c.pskHex == channel.pskHex)) {
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(context.l10n.channels_qrExists(channel.name)),
|
||||
);
|
||||
return SharedChannelAdd.alreadyExists;
|
||||
}
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(dialogContext.l10n.channels_addChannel),
|
||||
content: Text(dialogContext.l10n.channels_qrAddConfirm(channel.name)),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: Text(dialogContext.l10n.common_cancel),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
child: Text(dialogContext.l10n.common_add),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed != true || !context.mounted) return SharedChannelAdd.cancelled;
|
||||
final slot = allocateChannelSlotOrExplain(
|
||||
context,
|
||||
connector,
|
||||
psk: channel.psk,
|
||||
);
|
||||
if (slot == null) return SharedChannelAdd.refused;
|
||||
final result = await connector.setChannel(slot, channel.name, channel.psk);
|
||||
if (!context.mounted) return SharedChannelAdd.refused;
|
||||
if (explainUnconfirmedChannelWrite(context, result)) {
|
||||
return SharedChannelAdd.refused;
|
||||
}
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(context.l10n.channels_qrAdded(channel.name)),
|
||||
backgroundColor: Colors.green,
|
||||
);
|
||||
return SharedChannelAdd.added;
|
||||
}
|
||||
@ -0,0 +1,130 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../connector/meshcore_protocol.dart';
|
||||
import '../models/channel.dart';
|
||||
import '../models/contact.dart';
|
||||
|
||||
/// A share link Offband can act on.
|
||||
sealed class ShareLink {
|
||||
const ShareLink();
|
||||
|
||||
/// What the link adds, for "Connect a radio to add ...", or null when the
|
||||
/// link does not say.
|
||||
String? get displayName;
|
||||
}
|
||||
|
||||
class ChannelShareLink extends ShareLink {
|
||||
const ChannelShareLink(this.channel);
|
||||
final Channel channel;
|
||||
|
||||
@override
|
||||
String get displayName => channel.name;
|
||||
}
|
||||
|
||||
class ContactShareLink extends ShareLink {
|
||||
const ContactShareLink(this.uri, this.contact);
|
||||
|
||||
/// The link as received. The add-contact dialog parses it again itself, so
|
||||
/// a link and a paste fill the dialog the same way.
|
||||
final String uri;
|
||||
final Contact contact;
|
||||
|
||||
@override
|
||||
String get displayName => contact.name;
|
||||
}
|
||||
|
||||
/// The older `meshcore://<signed advert hex>` form, which "Copy Advert to
|
||||
/// Clipboard" still produces. The radio imports it as is, so it is carried
|
||||
/// as bytes; the name is inside the signed advert and only the radio reads
|
||||
/// it.
|
||||
class AdvertShareLink extends ShareLink {
|
||||
const AdvertShareLink(this.advert);
|
||||
final Uint8List advert;
|
||||
|
||||
@override
|
||||
String? get displayName => null;
|
||||
}
|
||||
|
||||
// An advert is at least 98 bytes: key, timestamp, signature, flags. It fits
|
||||
// in one radio packet, so anything past 255 bytes is not one.
|
||||
final _advertLink = RegExp(r'^meshcore://((?:[0-9a-fA-F]{2}){98,255})$');
|
||||
|
||||
/// Parses [raw] into a link Offband can add, or null if it is not one.
|
||||
ShareLink? parseShareLink(String raw) {
|
||||
final trimmed = raw.trim();
|
||||
final channel = Channel.fromShareUri(trimmed);
|
||||
if (channel != null) return ChannelShareLink(channel);
|
||||
final contact = Contact.fromShareUri(trimmed);
|
||||
if (contact != null) return ContactShareLink(trimmed, contact);
|
||||
final advert = _advertLink.firstMatch(trimmed);
|
||||
if (advert != null) return AdvertShareLink(hex2Uint8List(advert[1]!));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The one place a share link goes, wherever it came from: a tap in a
|
||||
/// message, the OS, the web client's address bar (#1289).
|
||||
///
|
||||
/// A link is never acted on here. It is held until the app can show its
|
||||
/// confirmation, and `LinkRouterHost` shows it. Only the latest link is held,
|
||||
/// and only in memory: an old link must not pop up days later.
|
||||
class LinkRouter extends ChangeNotifier {
|
||||
ShareLink? _pending;
|
||||
bool _pendingAnnounced = false;
|
||||
String? _rejected;
|
||||
|
||||
ShareLink? get pending => _pending;
|
||||
|
||||
/// True once the user has been told the pending link is waiting for a
|
||||
/// radio, so the message is shown once per link, not on every change.
|
||||
bool get pendingAnnounced => _pendingAnnounced;
|
||||
|
||||
/// Takes a link from any source. Returns false if it is not one Offband
|
||||
/// can add; the host then tells the user so.
|
||||
bool handle(String raw) {
|
||||
final link = parseShareLink(raw);
|
||||
if (link == null) {
|
||||
_rejected = raw;
|
||||
} else {
|
||||
_pending = link;
|
||||
_pendingAnnounced = false;
|
||||
}
|
||||
notifyListeners();
|
||||
return link != null;
|
||||
}
|
||||
|
||||
/// Takes a link the OS opened the app with (#1291). Only share links are
|
||||
/// acted on: the OS also reports ordinary launches, and on web the page's
|
||||
/// own address arrives as the "initial link", neither of which is the
|
||||
/// user asking to add anything, so they are ignored rather than reported.
|
||||
void handleFromOs(Uri uri) {
|
||||
if (uri.scheme.toLowerCase() != 'meshcore') return;
|
||||
handle(uri.toString());
|
||||
}
|
||||
|
||||
/// The pending link if its confirmation can be shown now, removing it.
|
||||
///
|
||||
/// Adding anything needs a connected radio. A channel also waits for the
|
||||
/// channel table to settle: right after connecting, the connector empties
|
||||
/// its channel list while it syncs, so a duplicate check would miss a
|
||||
/// channel the radio already has, and the slot picker would refuse.
|
||||
ShareLink? takeIfReady({
|
||||
required bool connected,
|
||||
required bool channelTableBusy,
|
||||
}) {
|
||||
final link = _pending;
|
||||
if (link == null || !connected) return null;
|
||||
if (link is ChannelShareLink && channelTableBusy) return null;
|
||||
_pending = null;
|
||||
_pendingAnnounced = false;
|
||||
return link;
|
||||
}
|
||||
|
||||
void markPendingAnnounced() => _pendingAnnounced = true;
|
||||
|
||||
/// The last link that could not be parsed, removing it.
|
||||
String? takeRejected() {
|
||||
final rejected = _rejected;
|
||||
_rejected = null;
|
||||
return rejected;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,153 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../connector/meshcore_protocol.dart';
|
||||
import '../helpers/channel_share_add.dart';
|
||||
import '../helpers/snack_bar_builder.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../services/link_router.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import 'add_contact_by_key_dialog.dart';
|
||||
import 'contact_add_feedback.dart';
|
||||
|
||||
/// Shows the confirmation for a share link held by [LinkRouter] as soon as
|
||||
/// one can be shown, and says why when it cannot (#1289).
|
||||
///
|
||||
/// It wraps the home route, so it sits below the Navigator and its dialogs
|
||||
/// and messages open over whatever screen is on top.
|
||||
class LinkRouterHost extends StatefulWidget {
|
||||
const LinkRouterHost({super.key, required this.child, this.osLinks});
|
||||
|
||||
final Widget child;
|
||||
|
||||
/// Links the OS opened the app with: the one that launched it, then any
|
||||
/// that arrive while it runs (#1291). Null in tests that do not need it.
|
||||
final Stream<Uri>? osLinks;
|
||||
|
||||
@override
|
||||
State<LinkRouterHost> createState() => _LinkRouterHostState();
|
||||
}
|
||||
|
||||
class _LinkRouterHostState extends State<LinkRouterHost> {
|
||||
late final LinkRouter _router;
|
||||
late final MeshCoreConnector _connector;
|
||||
StreamSubscription<Uri>? _osLinks;
|
||||
bool _scheduled = false;
|
||||
bool _showing = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_router = context.read<LinkRouter>();
|
||||
_connector = context.read<MeshCoreConnector>();
|
||||
_router.addListener(_schedule);
|
||||
_connector.addListener(_schedule);
|
||||
_osLinks = widget.osLinks?.listen(
|
||||
_router.handleFromOs,
|
||||
onError: (Object e) =>
|
||||
appLogger.warn('OS link stream error: $e', tag: 'LinkRouter'),
|
||||
);
|
||||
_schedule();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_osLinks?.cancel();
|
||||
_router.removeListener(_schedule);
|
||||
_connector.removeListener(_schedule);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// Listeners can fire mid-build; dialogs open after the frame.
|
||||
void _schedule() {
|
||||
if (_scheduled) return;
|
||||
_scheduled = true;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_scheduled = false;
|
||||
if (mounted) _check();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _check() async {
|
||||
if (_showing) return;
|
||||
final l10n = context.l10n;
|
||||
if (_router.takeRejected() != null) {
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(l10n.link_invalid),
|
||||
persist: true,
|
||||
);
|
||||
}
|
||||
final link = _router.takeIfReady(
|
||||
connected: _connector.isConnected,
|
||||
channelTableBusy: _connector.isChannelTableBusy,
|
||||
);
|
||||
if (link == null) {
|
||||
final waiting = _router.pending;
|
||||
if (waiting != null && !_router.pendingAnnounced) {
|
||||
_router.markPendingAnnounced();
|
||||
final name = waiting.displayName;
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(
|
||||
name == null
|
||||
? l10n.link_waitingForRadioContact
|
||||
: l10n.link_waitingForRadio(name),
|
||||
),
|
||||
persist: true,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
_showing = true;
|
||||
try {
|
||||
switch (link) {
|
||||
case ChannelShareLink(:final channel):
|
||||
await confirmAndAddSharedChannel(context, channel);
|
||||
case ContactShareLink(:final uri):
|
||||
await showAddContactByKeyDialog(context, initialKeyText: uri);
|
||||
case AdvertShareLink(:final advert):
|
||||
await _importAdvert(advert);
|
||||
}
|
||||
} finally {
|
||||
_showing = false;
|
||||
}
|
||||
// A link that arrived while this one was open.
|
||||
if (mounted) _schedule();
|
||||
}
|
||||
|
||||
/// The same import "Add Contact from Clipboard" does, after a confirmation.
|
||||
Future<void> _importAdvert(Uint8List advert) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(dialogContext.l10n.link_addContactTitle),
|
||||
content: Text(dialogContext.l10n.link_importAdvertConfirm),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: Text(dialogContext.l10n.common_cancel),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
child: Text(dialogContext.l10n.common_add),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed != true || !mounted) return;
|
||||
await addContactWithFeedback(
|
||||
context,
|
||||
_connector,
|
||||
'',
|
||||
() => _connector.importContact(buildImportContactFrame(advert)),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => widget.child;
|
||||
}
|
||||
@ -0,0 +1,68 @@
|
||||
import 'package:flutter_linkify/flutter_linkify.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/helpers/link_handler.dart';
|
||||
|
||||
// #1289: a meshcore:// link in a message is tappable. The stock URL
|
||||
// linkifier only finds http(s) and www, so before this the link was plain
|
||||
// text.
|
||||
|
||||
const _link = 'meshcore://channel/add?name=%23example';
|
||||
|
||||
/// The same chain, in the same order, LinkHandler gives Linkify.
|
||||
List<LinkifyElement> _parse(String text) {
|
||||
const options = LinkifyOptions(humanize: false, defaultToHttps: false);
|
||||
var elements = <LinkifyElement>[TextElement(text)];
|
||||
for (final linkifier in const <Linkifier>[
|
||||
MeshcoreLinkifier(),
|
||||
UrlLinkifier(),
|
||||
EmailLinkifier(),
|
||||
]) {
|
||||
elements = linkifier.parse(elements, options);
|
||||
}
|
||||
return elements;
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('finds a meshcore:// link in a sentence', () {
|
||||
final elements = _parse('join $_link now');
|
||||
final links = elements.whereType<UrlElement>().toList();
|
||||
expect(links.map((e) => e.url), [_link]);
|
||||
expect(elements.first, isA<TextElement>());
|
||||
expect((elements.first as TextElement).text, 'join ');
|
||||
expect((elements.last as TextElement).text, ' now');
|
||||
});
|
||||
|
||||
test('leaves a full stop after the link out of it', () {
|
||||
final elements = _parse('Join $_link.');
|
||||
expect(elements.whereType<UrlElement>().single.url, _link);
|
||||
expect((elements.last as TextElement).text, '.');
|
||||
});
|
||||
|
||||
test('finds several links and still finds web links', () {
|
||||
final elements = _parse(
|
||||
'$_link and https://offband.org and meshcore://contact/add?name=B',
|
||||
);
|
||||
expect(elements.whereType<UrlElement>().map((e) => e.url), [
|
||||
_link,
|
||||
'https://offband.org',
|
||||
'meshcore://contact/add?name=B',
|
||||
]);
|
||||
});
|
||||
|
||||
test('leaves a closing bracket around the link out of it', () {
|
||||
final elements = _parse('(see $_link).');
|
||||
expect(elements.whereType<UrlElement>().single.url, _link);
|
||||
expect((elements.last as TextElement).text, ').');
|
||||
});
|
||||
|
||||
test('keeps a bracket the link itself opened', () {
|
||||
const named = 'meshcore://channel/add?name=%23a(b)';
|
||||
expect(_parse('join $named').whereType<UrlElement>().single.url, named);
|
||||
});
|
||||
|
||||
test('plain text is left alone', () {
|
||||
final elements = _parse('no links here');
|
||||
expect(elements, hasLength(1));
|
||||
expect((elements.single as TextElement).text, 'no links here');
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,59 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
// #1291: the OS only hands a meshcore:// link to Offband if the app declares
|
||||
// the scheme. Before this, none of the platforms did, so a tapped link went
|
||||
// nowhere. Flutter's own deep-link routing must also be off where app_links
|
||||
// needs it, or Flutter treats "channel/add" as a screen to navigate to.
|
||||
|
||||
String _read(String path) => File(path).readAsStringSync();
|
||||
|
||||
/// The `<intent-filter>` blocks in the Android manifest.
|
||||
Iterable<String> _intentFilters(String manifest) => RegExp(
|
||||
r'<intent-filter>([\s\S]*?)</intent-filter>',
|
||||
).allMatches(manifest).map((m) => m[1]!);
|
||||
|
||||
/// True if a `CFBundleURLSchemes` array in [plist] lists [scheme].
|
||||
bool _plistDeclaresScheme(String plist, String scheme) => RegExp(
|
||||
r'<key>CFBundleURLSchemes</key>\s*<array>[\s\S]*?<string>' +
|
||||
RegExp.escape(scheme) +
|
||||
r'</string>[\s\S]*?</array>',
|
||||
).hasMatch(plist);
|
||||
|
||||
void main() {
|
||||
test('Android opens meshcore:// links in Offband', () {
|
||||
final manifest = _read('android/app/src/main/AndroidManifest.xml');
|
||||
final filter = _intentFilters(
|
||||
manifest,
|
||||
).where((f) => f.contains('android:scheme="meshcore"'));
|
||||
expect(filter, hasLength(1), reason: 'one meshcore intent filter');
|
||||
expect(filter.single, contains('android.intent.action.VIEW'));
|
||||
expect(filter.single, contains('android.intent.category.BROWSABLE'));
|
||||
expect(filter.single, contains('android.intent.category.DEFAULT'));
|
||||
expect(
|
||||
manifest,
|
||||
matches(
|
||||
RegExp(
|
||||
r'android:name="flutter_deeplinking_enabled"\s+android:value="false"',
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('iOS opens meshcore:// links in Offband', () {
|
||||
final plist = _read('ios/Runner/Info.plist');
|
||||
expect(_plistDeclaresScheme(plist, 'meshcore'), isTrue);
|
||||
expect(
|
||||
plist,
|
||||
matches(RegExp(r'<key>FlutterDeepLinkingEnabled</key>\s*<false/>')),
|
||||
);
|
||||
});
|
||||
|
||||
test('macOS opens meshcore:// links in Offband', () {
|
||||
expect(
|
||||
_plistDeclaresScheme(_read('macos/Runner/Info.plist'), 'meshcore'),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,127 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/channel.dart';
|
||||
import 'package:meshcore_open/services/link_router.dart';
|
||||
|
||||
// #1289: every share link goes through LinkRouter, which holds it until its
|
||||
// confirmation can be shown and never adds anything itself.
|
||||
|
||||
const _key = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
|
||||
const _channelLink =
|
||||
'meshcore://channel/add?name=%23echo&secret=5d25cf40b1f5b4a7eb0cf9703634a948';
|
||||
const _hashtagLink = 'meshcore://channel/add?name=%23example';
|
||||
const _contactLink = 'meshcore://contact/add?name=Bob&public_key=$_key&type=1';
|
||||
final _advertLink = 'meshcore://${'ab' * 98}';
|
||||
|
||||
void main() {
|
||||
group('parseShareLink', () {
|
||||
test('reads every link form Offband produces or accepts', () {
|
||||
expect(parseShareLink(_channelLink), isA<ChannelShareLink>());
|
||||
final hashtag = parseShareLink(_hashtagLink) as ChannelShareLink;
|
||||
expect(
|
||||
hashtag.channel.pskHex,
|
||||
Channel(
|
||||
index: 0,
|
||||
name: '#example',
|
||||
psk: Channel.derivePskFromHashtag('example'),
|
||||
).pskHex,
|
||||
);
|
||||
final contact = parseShareLink(_contactLink) as ContactShareLink;
|
||||
expect(contact.contact.name, 'Bob');
|
||||
expect(contact.uri, _contactLink);
|
||||
final advert = parseShareLink(_advertLink) as AdvertShareLink;
|
||||
expect(advert.advert.length, 98);
|
||||
});
|
||||
|
||||
test('tolerates surrounding whitespace', () {
|
||||
expect(parseShareLink(' $_channelLink\n'), isA<ChannelShareLink>());
|
||||
});
|
||||
|
||||
test('rejects anything else', () {
|
||||
for (final bad in [
|
||||
'https://example.com',
|
||||
'meshcore://channel/add?name=x',
|
||||
'meshcore://contact/add?name=Bob',
|
||||
'meshcore://${'ab' * 10}',
|
||||
'meshcore://${'ab' * 98}a',
|
||||
// Longer than any radio packet: not an advert.
|
||||
'meshcore://${'ab' * 256}',
|
||||
'meshcore://zz',
|
||||
'',
|
||||
]) {
|
||||
expect(parseShareLink(bad), isNull, reason: bad);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
group('LinkRouter', () {
|
||||
test('a malformed link is reported, not dropped', () {
|
||||
final router = LinkRouter();
|
||||
var notified = 0;
|
||||
router.addListener(() => notified++);
|
||||
expect(router.handle('meshcore://nope'), isFalse);
|
||||
expect(notified, 1);
|
||||
expect(router.pending, isNull);
|
||||
expect(router.takeRejected(), 'meshcore://nope');
|
||||
expect(router.takeRejected(), isNull);
|
||||
});
|
||||
|
||||
test('a link is held while no radio is connected', () {
|
||||
final router = LinkRouter()..handle(_channelLink);
|
||||
expect(
|
||||
router.takeIfReady(connected: false, channelTableBusy: false),
|
||||
isNull,
|
||||
);
|
||||
expect(router.pending, isA<ChannelShareLink>());
|
||||
final link = router.takeIfReady(connected: true, channelTableBusy: false);
|
||||
expect(link, isA<ChannelShareLink>());
|
||||
expect(router.pending, isNull);
|
||||
});
|
||||
|
||||
test('a channel link waits for the channel table to settle', () {
|
||||
final router = LinkRouter()..handle(_channelLink);
|
||||
expect(
|
||||
router.takeIfReady(connected: true, channelTableBusy: true),
|
||||
isNull,
|
||||
);
|
||||
expect(router.pending, isNotNull);
|
||||
});
|
||||
|
||||
test('a contact link does not wait for the channel table', () {
|
||||
final router = LinkRouter()..handle(_contactLink);
|
||||
expect(
|
||||
router.takeIfReady(connected: true, channelTableBusy: true),
|
||||
isA<ContactShareLink>(),
|
||||
);
|
||||
});
|
||||
|
||||
test('only the latest link is held, and it is announced afresh', () {
|
||||
final router = LinkRouter()..handle(_channelLink);
|
||||
router.markPendingAnnounced();
|
||||
expect(router.pendingAnnounced, isTrue);
|
||||
router.handle(_contactLink);
|
||||
expect(router.pending, isA<ContactShareLink>());
|
||||
expect(router.pendingAnnounced, isFalse);
|
||||
});
|
||||
|
||||
test('from the OS, only share links are acted on (#1291)', () {
|
||||
final router = LinkRouter();
|
||||
// An ordinary launch, and on web the page's own address.
|
||||
router.handleFromOs(Uri.parse('https://offband.app/'));
|
||||
router.handleFromOs(Uri.parse('offband://open'));
|
||||
expect(router.pending, isNull);
|
||||
expect(router.takeRejected(), isNull, reason: 'not reported either');
|
||||
|
||||
router.handleFromOs(Uri.parse(_hashtagLink));
|
||||
expect(router.pending, isA<ChannelShareLink>());
|
||||
|
||||
router.handleFromOs(Uri.parse('MESHCORE://channel/add?name=nope'));
|
||||
expect(router.takeRejected(), isNotNull, reason: 'a broken share link');
|
||||
});
|
||||
|
||||
test('a malformed link does not replace a held one', () {
|
||||
final router = LinkRouter()..handle(_channelLink);
|
||||
router.handle('meshcore://nope');
|
||||
expect(router.pending, isA<ChannelShareLink>());
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,193 @@
|
||||
// #1289: a share link opens the existing confirmation, waits for a radio
|
||||
// when none is connected, and never adds anything the user did not confirm.
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/helpers/link_handler.dart';
|
||||
import 'package:meshcore_open/l10n/app_localizations.dart';
|
||||
import 'package:meshcore_open/models/channel.dart';
|
||||
import 'package:meshcore_open/services/link_router.dart';
|
||||
import 'package:meshcore_open/widgets/link_router_host.dart';
|
||||
|
||||
const _link = 'meshcore://channel/add?name=%23example';
|
||||
|
||||
class _Radio extends MeshCoreConnector {
|
||||
bool connected = false;
|
||||
bool busy = false;
|
||||
final List<Channel> onRadio = [];
|
||||
final List<(int, String, String)> writes = [];
|
||||
|
||||
void change() => notifyListeners();
|
||||
|
||||
@override
|
||||
bool get isConnected => connected;
|
||||
@override
|
||||
bool get isChannelTableBusy => busy;
|
||||
@override
|
||||
List<Channel> get channels => List.unmodifiable(onRadio);
|
||||
@override
|
||||
int get maxChannels => 8;
|
||||
@override
|
||||
Future<ChannelWrite> setChannel(
|
||||
int index,
|
||||
String name,
|
||||
Uint8List psk, {
|
||||
bool refresh = true,
|
||||
}) async {
|
||||
writes.add((
|
||||
index,
|
||||
name,
|
||||
Channel(index: index, name: name, psk: psk).pskHex,
|
||||
));
|
||||
return ChannelWrite.ok;
|
||||
}
|
||||
}
|
||||
|
||||
Future<(LinkRouter, BuildContext)> _pump(
|
||||
WidgetTester tester,
|
||||
_Radio radio,
|
||||
) async {
|
||||
final router = LinkRouter();
|
||||
late BuildContext inner;
|
||||
await tester.pumpWidget(
|
||||
MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<MeshCoreConnector>.value(value: radio),
|
||||
ChangeNotifierProvider.value(value: router),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: LinkRouterHost(
|
||||
child: Scaffold(
|
||||
body: Builder(
|
||||
builder: (context) {
|
||||
inner = context;
|
||||
return const SizedBox.expand();
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
return (router, inner);
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('waits for a radio, then confirms, then writes', (tester) async {
|
||||
final radio = _Radio();
|
||||
final (router, _) = await _pump(tester, radio);
|
||||
|
||||
router.handle(_link);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.textContaining('Connect a radio to add #example'), findsOne);
|
||||
expect(find.byType(AlertDialog), findsNothing);
|
||||
|
||||
radio
|
||||
..connected = true
|
||||
..busy = true
|
||||
..change();
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(AlertDialog), findsNothing, reason: 'table busy');
|
||||
|
||||
radio
|
||||
..busy = false
|
||||
..change();
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Add channel "#example"?'), findsOne);
|
||||
expect(radio.writes, isEmpty, reason: 'nothing before confirming');
|
||||
|
||||
await tester.tap(find.widgetWithText(FilledButton, 'Add'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(radio.writes, hasLength(1));
|
||||
expect(radio.writes.single.$2, '#example');
|
||||
expect(
|
||||
radio.writes.single.$3,
|
||||
Channel(
|
||||
index: 0,
|
||||
name: '#example',
|
||||
psk: Channel.derivePskFromHashtag('example'),
|
||||
).pskHex,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('cancel writes nothing', (tester) async {
|
||||
final radio = _Radio()..connected = true;
|
||||
final (router, _) = await _pump(tester, radio);
|
||||
router.handle(_link);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.widgetWithText(TextButton, 'Cancel'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(radio.writes, isEmpty);
|
||||
expect(router.pending, isNull);
|
||||
});
|
||||
|
||||
testWidgets('a channel already on the radio is not offered again', (
|
||||
tester,
|
||||
) async {
|
||||
final radio = _Radio()..connected = true;
|
||||
radio.onRadio.add(Channel.fromShareUri(_link, index: 1)!);
|
||||
final (router, _) = await _pump(tester, radio);
|
||||
router.handle(_link);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(AlertDialog), findsNothing);
|
||||
expect(find.text('"#example" is already added.'), findsOne);
|
||||
expect(radio.writes, isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('a malformed link says so', (tester) async {
|
||||
final radio = _Radio()..connected = true;
|
||||
final (router, _) = await _pump(tester, radio);
|
||||
router.handle('meshcore://channel/add?name=nope');
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.textContaining("isn't a channel or contact"), findsOne);
|
||||
});
|
||||
|
||||
testWidgets('a link from the OS opens the confirmation (#1291)', (
|
||||
tester,
|
||||
) async {
|
||||
final radio = _Radio()..connected = true;
|
||||
final os = StreamController<Uri>();
|
||||
addTearDown(os.close);
|
||||
await tester.pumpWidget(
|
||||
MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<MeshCoreConnector>.value(value: radio),
|
||||
ChangeNotifierProvider(create: (_) => LinkRouter()),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: LinkRouterHost(osLinks: os.stream, child: const Scaffold()),
|
||||
),
|
||||
),
|
||||
);
|
||||
os.add(Uri.parse('https://offband.app/'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(AlertDialog), findsNothing);
|
||||
expect(find.textContaining("isn't a channel"), findsNothing);
|
||||
|
||||
os.add(Uri.parse(_link));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Add channel "#example"?'), findsOne);
|
||||
});
|
||||
|
||||
testWidgets('tapping a meshcore:// link in a message routes it here', (
|
||||
tester,
|
||||
) async {
|
||||
final radio = _Radio()..connected = true;
|
||||
final (_, inner) = await _pump(tester, radio);
|
||||
LinkHandler.handleLinkTap(inner, _link);
|
||||
await tester.pumpAndSettle();
|
||||
// Offband's own confirmation, not the browser's "Open Link" dialog.
|
||||
expect(find.text('Add channel "#example"?'), findsOne);
|
||||
expect(find.text('Open Link'), findsNothing);
|
||||
});
|
||||
}
|
||||
Loading…
Reference in new issue