feat(link): add the phone client for desktop discovery and pairing

Phones find Mornye on a computer over mDNS (bonsoir, _mornye._tcp),
pair with its 6-digit PIN and keep a live session with the chosen
desktop.

- Pinned HTTPS: first contact records the presented certificate and
  checks it against info and the mDNS fingerprint; later requests and
  the WebSocket accept only that SHA-256.
- Pairing posts the PIN proof, maps bad_proof, pairing_closed and 429
  to clear errors, saves a Subsonic API-key network connection, adds it
  to Library and scans it. Re-pairing replaces the key in place.
- LinkClientSession: Bearer JSON get/post with timeouts and
  LinkException mapping, WebSocket hello/welcome, backoff from 1 s
  doubling to 30 s, pause in the background, reconnect when discovery
  sees the desktop again, address updates when it moves.
- LinkClientController publishes the active session through
  linkActiveClientProvider and rescans on catalog.changed.
- Settings entry "Mornye on your computer" on Android and iOS with
  nearby and paired computers, PIN and manual address dialogs, forget,
  and local network permission, Wi-Fi and certificate warnings.
- iOS NSBonjourServices and the Android multicast permission.
This commit is contained in:
zarzet committed 2026-10-25 02:37:07 +07:00
1 parent 47f61bf46a
commit 32fc942a04
27 files changed
+5525 -1

No files matched your search

+2
View File
@@ -13,6 +13,8 @@
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />
<!-- Mornye Link finds the desktop app over mDNS (multicast lock). -->
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="29" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
+4
View File
@@ -86,6 +86,10 @@
<key>NSLocalNetworkUsageDescription</key>
<string>Connect to your music servers and network storage to browse and play your music.</string>
<key>NSBonjourServices</key>
<array>
<string>_mornye._tcp</string>
</array>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
+231
View File
@@ -7835,5 +7835,236 @@
"desktopShortcutToggleSidebar": "Show or hide sidebar",
"@desktopShortcutToggleSidebar": {
"description": "Keyboard Shortcuts row for the shortcut that collapses or expands the desktop sidebar"
},
"linkSettingsTitle": "Mornye on your computer",
"@linkSettingsTitle": {
"description": "Phone Settings entry that pairs the phone with the Mornye desktop app on the local network"
},
"linkSettingsSubtitle": "Play and control your computer's library",
"@linkSettingsSubtitle": {
"description": "Subtitle of the Mornye on your computer entry in phone Settings"
},
"linkPageTitle": "Computers",
"@linkPageTitle": {
"description": "Title of the page listing computers running Mornye that the phone can pair with; kept short for the large title"
},
"linkPageDescription": "Pair with Mornye on your computer to play its library on this phone and control what it plays. Both devices need to be on the same network.",
"@linkPageDescription": {
"description": "Introduction at the top of the computers page"
},
"linkPairedSection": "Paired computers",
"@linkPairedSection": {
"description": "Section header for computers this phone is paired with"
},
"linkNearbySection": "On this network",
"@linkNearbySection": {
"description": "Section header for computers running Mornye found on the local network"
},
"linkSearching": "Looking for computers...",
"@linkSearching": {
"description": "Row shown while the phone searches the local network for computers"
},
"linkNoneFoundTitle": "No computers found",
"@linkNoneFoundTitle": {
"description": "Row shown when the phone is not searching and found no computer"
},
"linkNoneFound": "Open Mornye on your computer and turn on Share with Mornye on your phone in its settings.",
"@linkNoneFound": {
"description": "Hint under the search row when no computer was found yet; Share with Mornye on your phone is the name of the desktop setting"
},
"linkAddManually": "Add by address",
"@linkAddManually": {
"description": "Button and dialog title for pairing with a computer by typing its address and port"
},
"linkManualHost": "Computer address",
"@linkManualHost": {
"description": "Field label for the computer's IP address or host name"
},
"linkManualPort": "Port",
"@linkManualPort": {
"description": "Field label for the network port of the Mornye desktop server"
},
"linkManualMessage": "Mornye on your computer shows its address and port where you turn on sharing.",
"@linkManualMessage": {
"description": "Explains where to find the address and port to type"
},
"linkContinue": "Continue",
"@linkContinue": {
"description": "Dialog action that continues to the PIN step after typing an address"
},
"linkStateConnected": "Connected",
"@linkStateConnected": {
"description": "Status of the paired computer that is connected"
},
"linkStateConnecting": "Connecting...",
"@linkStateConnecting": {
"description": "Status of the paired computer while the phone connects to it"
},
"linkStateDisconnected": "Not connected",
"@linkStateDisconnected": {
"description": "Status of the paired computer when it cannot be reached"
},
"linkStateInactive": "Tap to use this computer",
"@linkStateInactive": {
"description": "Status of a paired computer other than the one in use; tapping it makes it the one in use"
},
"linkActive": "In use",
"@linkActive": {
"description": "Label next to the paired computer the phone currently uses, shown when several are paired"
},
"linkForget": "Forget",
"@linkForget": {
"description": "Action that unpairs a computer from this phone"
},
"linkForgetTitle": "Forget {name}?",
"@linkForgetTitle": {
"description": "Title of the dialog confirming that a paired computer is forgotten",
"placeholders": {
"name": {
"type": "String"
}
}
},
"linkForgetMessage": "This phone stops connecting to it. You can pair again later.",
"@linkForgetMessage": {
"description": "Explanation in the forget computer dialog"
},
"linkForgetRemoveLibrary": "Also remove its music from Library",
"@linkForgetRemoveLibrary": {
"description": "Switch in the forget computer dialog that also removes the computer's network connection and Library source"
},
"linkPinTitle": "Pair with {name}",
"@linkPinTitle": {
"description": "Title of the dialog asking for the pairing PIN",
"placeholders": {
"name": {
"type": "String"
}
}
},
"linkPinMessage": "Enter the 6-digit PIN shown on your computer.",
"@linkPinMessage": {
"description": "Instruction in the pairing PIN dialog"
},
"linkPinField": "PIN",
"@linkPinField": {
"description": "Label of the pairing PIN field"
},
"linkPinCode": "Your computer shows the code {code} next to the PIN. Pair only if it matches.",
"@linkPinCode": {
"description": "Security check in the PIN dialog; the placeholder is 8 hexadecimal characters of the computer's certificate fingerprint",
"placeholders": {
"code": {
"type": "String"
}
}
},
"linkPinNotOpen": "Pairing is not open yet. Start pairing in Mornye on your computer to show a PIN.",
"@linkPinNotOpen": {
"description": "Note in the PIN dialog when the computer reports that no pairing window is open"
},
"linkPair": "Pair",
"@linkPair": {
"description": "Action that sends the PIN to pair with the computer"
},
"linkPaired": "Paired with {name}. Its music is being added to Library.",
"@linkPaired": {
"description": "Message after pairing succeeded",
"placeholders": {
"name": {
"type": "String"
}
}
},
"linkPairAgain": "Pair again",
"@linkPairAgain": {
"description": "Action that repeats pairing with a computer that no longer accepts this phone"
},
"linkErrorBadPin": "That PIN is not right. Check the PIN on your computer and try again.",
"@linkErrorBadPin": {
"description": "Pairing error when the PIN is wrong"
},
"linkErrorPairingClosed": "Pairing is not open on your computer. Start pairing there, then try again.",
"@linkErrorPairingClosed": {
"description": "Pairing error when the computer has no pairing window open"
},
"linkErrorTooManyAttempts": "Too many attempts. Wait a moment, then try again.",
"@linkErrorTooManyAttempts": {
"description": "Pairing error when the computer rate limits pairing attempts"
},
"linkErrorCertificateTitle": "Computer not verified",
"@linkErrorCertificateTitle": {
"description": "Title of the warning shown when the computer's certificate does not match what it reported"
},
"linkErrorCertificate": "The computer's security certificate does not match what it reported. Someone on this network may be intercepting the connection, so pairing stopped.",
"@linkErrorCertificate": {
"description": "Warning shown when the certificate seen during the connection differs from the computer's reported fingerprint"
},
"linkErrorIncompatible": "This computer runs a Mornye version that cannot pair with this phone. Update Mornye on both devices.",
"@linkErrorIncompatible": {
"description": "Pairing error when the computer is not a compatible Mornye desktop"
},
"linkErrorUnreachable": "The computer could not be reached. Check that Mornye is open on it and that both devices are on the same network.",
"@linkErrorUnreachable": {
"description": "Pairing error when the computer cannot be reached"
},
"linkErrorTimeout": "The computer did not answer in time. Try again.",
"@linkErrorTimeout": {
"description": "Pairing error when the computer does not answer"
},
"linkErrorInvalidAddress": "Enter a valid address and port, such as 192.168.1.20 and 47710.",
"@linkErrorInvalidAddress": {
"description": "Error for an address or port that cannot be used"
},
"linkErrorFailed": "Pairing failed. Try again.",
"@linkErrorFailed": {
"description": "Generic pairing error"
},
"linkLocalNetworkTitle": "Local network access needed",
"@linkLocalNetworkTitle": {
"description": "Title of the notice shown when the phone is not allowed to use the local network"
},
"linkLocalNetworkMessage": "Mornye needs local network access to find your computer and connect to it.",
"@linkLocalNetworkMessage": {
"description": "Explains why local network access is needed"
},
"linkLocalNetworkAllow": "Allow access",
"@linkLocalNetworkAllow": {
"description": "Button that asks for local network access again"
},
"linkWifiOffTitle": "Not on Wi-Fi",
"@linkWifiOffTitle": {
"description": "Title of the notice shown when the phone is not connected to Wi-Fi or Ethernet"
},
"linkWifiOffMessage": "Connect this phone to the same Wi-Fi network as your computer.",
"@linkWifiOffMessage": {
"description": "Explains that the phone must join the computer's Wi-Fi network"
},
"linkIssueUnauthorized": "{name} no longer accepts this phone. Pair again to reconnect.",
"@linkIssueUnauthorized": {
"description": "Notice when the paired computer refuses the phone's key",
"placeholders": {
"name": {
"type": "String"
}
}
},
"linkIssueCertificate": "{name} presented a different security certificate. Pair again only if you reinstalled or reset Mornye on that computer.",
"@linkIssueCertificate": {
"description": "Warning when a paired computer's certificate changed",
"placeholders": {
"name": {
"type": "String"
}
}
},
"linkIssueIncompatible": "Update Mornye on this phone and on {name} to connect.",
"@linkIssueIncompatible": {
"description": "Notice when the paired computer speaks another protocol version",
"placeholders": {
"name": {
"type": "String"
}
}
}
}
+50 -1
View File
@@ -7391,5 +7391,54 @@
"settingsKeyboardShortcutsSubtitle": "Tombol untuk pemutaran, navigasi dan panel",
"desktopShortcutsNavigation": "Navigasi",
"desktopShortcutDismiss": "Tutup dialog atau halaman",
"desktopShortcutToggleSidebar": "Tampilkan atau sembunyikan sidebar"
"desktopShortcutToggleSidebar": "Tampilkan atau sembunyikan sidebar",
"linkSettingsTitle": "Mornye di komputer Anda",
"linkSettingsSubtitle": "Putar dan kendalikan pustaka komputer Anda",
"linkPageTitle": "Komputer",
"linkPageDescription": "Pasangkan dengan Mornye di komputer Anda untuk memutar pustakanya di ponsel ini dan mengendalikan yang diputarnya. Kedua perangkat harus berada di jaringan yang sama.",
"linkPairedSection": "Komputer terpasang",
"linkNearbySection": "Di jaringan ini",
"linkSearching": "Mencari komputer...",
"linkNoneFoundTitle": "Tidak ada komputer ditemukan",
"linkNoneFound": "Buka Mornye di komputer Anda dan aktifkan Bagikan dengan Mornye di ponsel Anda di pengaturannya.",
"linkAddManually": "Tambah lewat alamat",
"linkManualHost": "Alamat komputer",
"linkManualPort": "Port",
"linkManualMessage": "Mornye di komputer Anda menampilkan alamat dan port di tempat Anda mengaktifkan berbagi.",
"linkContinue": "Lanjutkan",
"linkStateConnected": "Terhubung",
"linkStateConnecting": "Menghubungkan...",
"linkStateDisconnected": "Tidak terhubung",
"linkStateInactive": "Ketuk untuk memakai komputer ini",
"linkActive": "Dipakai",
"linkForget": "Lupakan",
"linkForgetTitle": "Lupakan {name}?",
"linkForgetMessage": "Ponsel ini berhenti terhubung ke komputer tersebut. Anda dapat memasangkannya lagi nanti.",
"linkForgetRemoveLibrary": "Hapus juga musiknya dari Pustaka",
"linkPinTitle": "Pasangkan dengan {name}",
"linkPinMessage": "Masukkan PIN 6 digit yang tampil di komputer Anda.",
"linkPinField": "PIN",
"linkPinCode": "Komputer Anda menampilkan kode {code} di samping PIN. Pasangkan hanya jika kodenya sama.",
"linkPinNotOpen": "Pemasangan belum dibuka. Mulai pemasangan di Mornye pada komputer Anda untuk menampilkan PIN.",
"linkPair": "Pasangkan",
"linkPaired": "Terpasang dengan {name}. Musiknya sedang ditambahkan ke Pustaka.",
"linkPairAgain": "Pasangkan lagi",
"linkErrorBadPin": "PIN tersebut salah. Periksa PIN di komputer Anda dan coba lagi.",
"linkErrorPairingClosed": "Pemasangan tidak dibuka di komputer Anda. Mulai pemasangan di sana, lalu coba lagi.",
"linkErrorTooManyAttempts": "Terlalu banyak percobaan. Tunggu sebentar, lalu coba lagi.",
"linkErrorCertificateTitle": "Komputer tidak terverifikasi",
"linkErrorCertificate": "Sertifikat keamanan komputer tidak cocok dengan yang dilaporkannya. Seseorang di jaringan ini mungkin menyadap koneksi, jadi pemasangan dihentikan.",
"linkErrorIncompatible": "Komputer ini menjalankan versi Mornye yang tidak dapat dipasangkan dengan ponsel ini. Perbarui Mornye di kedua perangkat.",
"linkErrorUnreachable": "Komputer tidak dapat dijangkau. Pastikan Mornye terbuka di komputer dan kedua perangkat berada di jaringan yang sama.",
"linkErrorTimeout": "Komputer tidak menjawab tepat waktu. Coba lagi.",
"linkErrorInvalidAddress": "Masukkan alamat dan port yang valid, misalnya 192.168.1.20 dan 47710.",
"linkErrorFailed": "Pemasangan gagal. Coba lagi.",
"linkLocalNetworkTitle": "Perlu akses jaringan lokal",
"linkLocalNetworkMessage": "Mornye memerlukan akses jaringan lokal untuk menemukan komputer Anda dan terhubung ke sana.",
"linkLocalNetworkAllow": "Izinkan akses",
"linkWifiOffTitle": "Tidak terhubung ke Wi-Fi",
"linkWifiOffMessage": "Hubungkan ponsel ini ke jaringan Wi-Fi yang sama dengan komputer Anda.",
"linkIssueUnauthorized": "{name} tidak lagi menerima ponsel ini. Pasangkan lagi untuk terhubung kembali.",
"linkIssueCertificate": "{name} menampilkan sertifikat keamanan yang berbeda. Pasangkan lagi hanya jika Anda memasang ulang atau mengatur ulang Mornye di komputer tersebut.",
"linkIssueIncompatible": "Perbarui Mornye di ponsel ini dan di {name} untuk terhubung."
}
@@ -0,0 +1,404 @@
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mornye/l10n/l10n.dart';
import 'package:mornye/services/link/client/link_client_pairing.dart';
import 'package:mornye/services/link/link_protocol.dart';
import 'package:mornye/theme/mornye_theme.dart';
import 'package:mornye/widgets/app_alert_dialog.dart';
import 'package:mornye/widgets/app_progress_indicator.dart';
import 'package:mornye/widgets/app_switch.dart';
import 'package:mornye/widgets/app_text_field.dart';
/// The message for a pairing failure.
String linkPairingErrorMessage(AppLocalizations l10n, LinkPairingError error) =>
switch (error) {
LinkPairingError.badPin => l10n.linkErrorBadPin,
LinkPairingError.pairingClosed => l10n.linkErrorPairingClosed,
LinkPairingError.tooManyAttempts => l10n.linkErrorTooManyAttempts,
LinkPairingError.certificateMismatch => l10n.linkErrorCertificate,
LinkPairingError.incompatible => l10n.linkErrorIncompatible,
LinkPairingError.invalidAddress => l10n.linkErrorInvalidAddress,
LinkPairingError.localNetworkPermission =>
l10n.networkErrorLocalPermission,
LinkPairingError.unreachable => l10n.linkErrorUnreachable,
LinkPairingError.timeout => l10n.linkErrorTimeout,
LinkPairingError.failed => l10n.linkErrorFailed,
};
/// Host and port from what someone typed: `192.168.1.20`, `host:47710`,
/// `https://[fe80::2]:47710/` and the like. [portInput] is used when the
/// address carries no port. Null when either part is unusable.
({String host, int port})? linkParseManualAddress(
String hostInput,
String portInput,
) {
var text = hostInput.trim().replaceFirst(
RegExp(r'^[a-z]+://', caseSensitive: false),
'',
);
final slash = text.indexOf('/');
if (slash >= 0) text = text.substring(0, slash);
String host;
String? port;
final bracketed = RegExp(r'^\[([^\]]+)\](?::(\d+))?$').firstMatch(text);
if (bracketed != null) {
host = bracketed[1]!;
port = bracketed[2];
} else if (RegExp(r'^[^:]+:\d+$').hasMatch(text)) {
final colon = text.lastIndexOf(':');
host = text.substring(0, colon);
port = text.substring(colon + 1);
} else {
host = text;
}
host = host.trim();
final parsedPort = int.tryParse((port ?? portInput).trim());
if (host.isEmpty ||
parsedPort == null ||
parsedPort < 1 ||
parsedPort > 65535 ||
host.contains(RegExp(r'[\s@/?#]')) ||
(host.contains(':') && InternetAddress.tryParse(host) == null)) {
return null;
}
return (host: host, port: parsedPort);
}
/// Asks for the desktop's PIN and pairs. [onSubmit] answers null on success,
/// which pops `true`, or the error to show while the dialog stays open.
class LinkPinDialog extends StatefulWidget {
const LinkPinDialog({
super.key,
required this.serverName,
required this.shortFingerprint,
required this.pairingOpen,
required this.onSubmit,
});
static const fieldKey = ValueKey('link-pin-field');
final String serverName;
/// The fingerprint's first 8 hex characters, shown on the desktop too.
final String shortFingerprint;
/// Whether the desktop reported an open pairing window.
final bool pairingOpen;
final Future<LinkPairingError?> Function(String pin) onSubmit;
@override
State<LinkPinDialog> createState() => _LinkPinDialogState();
}
class _LinkPinDialogState extends State<LinkPinDialog> {
final _pin = TextEditingController();
var _busy = false;
LinkPairingError? _error;
bool get _complete => RegExp(r'^\d{6}$').hasMatch(_pin.text);
@override
void dispose() {
_pin.dispose();
super.dispose();
}
Future<void> _submit() async {
if (!_complete || _busy) return;
setState(() {
_busy = true;
_error = null;
});
final error = await widget.onSubmit(_pin.text);
if (!mounted) return;
if (error == null) {
Navigator.of(context).pop(true);
return;
}
setState(() {
_busy = false;
_error = error;
if (error == LinkPairingError.badPin) _pin.clear();
});
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final formatters = [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(6),
];
final pinStyle = theme.textTheme.headlineSmall?.copyWith(
letterSpacing: 8,
fontFeatures: const [FontFeature.tabularFigures()],
);
final field = context.isMornye
? CupertinoTextField(
key: LinkPinDialog.fieldKey,
controller: _pin,
enabled: !_busy,
autofocus: true,
placeholder: l10n.linkPinField,
keyboardType: TextInputType.number,
inputFormatters: formatters,
autofillHints: const [AutofillHints.oneTimeCode],
textAlign: TextAlign.center,
style: pinStyle,
padding: const EdgeInsets.all(12),
onChanged: (_) => setState(() {}),
onSubmitted: (_) => _submit(),
)
: Semantics(
label: l10n.linkPinField,
child: TextField(
key: LinkPinDialog.fieldKey,
controller: _pin,
enabled: !_busy,
autofocus: true,
keyboardType: TextInputType.number,
inputFormatters: formatters,
autofillHints: const [AutofillHints.oneTimeCode],
textAlign: TextAlign.center,
style: pinStyle,
decoration: InputDecoration(
labelText: l10n.linkPinField,
border: const OutlineInputBorder(),
),
onChanged: (_) => setState(() {}),
onSubmitted: (_) => _submit(),
),
);
final note = theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
);
return AppAlertDialog(
title: Text(l10n.linkPinTitle(widget.serverName)),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(l10n.linkPinMessage),
const SizedBox(height: 16),
field,
const SizedBox(height: 12),
Text(l10n.linkPinCode(widget.shortFingerprint), style: note),
if (!widget.pairingOpen) ...[
const SizedBox(height: 8),
Text(l10n.linkPinNotOpen, style: note),
],
if (_error case final error?) ...[
const SizedBox(height: 12),
Text(
linkPairingErrorMessage(l10n, error),
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.error,
),
),
],
if (_busy) ...[
const SizedBox(height: 12),
const AppProgressIndicator.linear(),
],
],
),
actions: [
AppDialogAction(
onPressed: _busy ? null : () => Navigator.of(context).pop(false),
child: Text(l10n.dialogCancel),
),
AppDialogAction(
filled: true,
onPressed: _busy || !_complete ? null : _submit,
child: Text(l10n.linkPair),
),
],
);
}
}
/// Asks for a desktop's address and port, for networks without mDNS and
/// emulators. Pops the parsed address, or null when cancelled.
class LinkManualAddDialog extends StatefulWidget {
const LinkManualAddDialog({super.key});
static const hostKey = ValueKey('link-manual-host');
static const portKey = ValueKey('link-manual-port');
@override
State<LinkManualAddDialog> createState() => _LinkManualAddDialogState();
}
class _LinkManualAddDialogState extends State<LinkManualAddDialog> {
final _host = TextEditingController();
final _port = TextEditingController(text: '$linkPortFirst');
var _invalid = false;
@override
void dispose() {
_host.dispose();
_port.dispose();
super.dispose();
}
void _submit() {
final address = linkParseManualAddress(_host.text, _port.text);
if (address == null) {
setState(() => _invalid = true);
return;
}
Navigator.of(context).pop(address);
}
Widget _field(
Key key,
TextEditingController controller,
String label, {
required TextInputType keyboardType,
String? hint,
bool last = false,
}) {
if (context.isMornye) {
return CupertinoTextField(
key: key,
controller: controller,
placeholder: hint ?? label,
keyboardType: keyboardType,
autocorrect: false,
enableSuggestions: false,
padding: const EdgeInsets.all(12),
textInputAction: last ? TextInputAction.done : TextInputAction.next,
onSubmitted: last ? (_) => _submit() : null,
);
}
return AppTextField(
key: key,
controller: controller,
label: label,
hint: hint,
keyboardType: keyboardType,
autocorrect: false,
outlined: true,
textInputAction: last ? TextInputAction.done : TextInputAction.next,
onSubmitted: last ? (_) => _submit() : null,
decoration: InputDecoration(
labelText: label,
hintText: hint,
border: const OutlineInputBorder(),
),
);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
return AppAlertDialog(
title: Text(l10n.linkAddManually),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(l10n.linkManualMessage),
const SizedBox(height: 16),
_field(
LinkManualAddDialog.hostKey,
_host,
l10n.linkManualHost,
hint: '192.168.1.20',
keyboardType: TextInputType.url,
),
const SizedBox(height: 12),
_field(
LinkManualAddDialog.portKey,
_port,
l10n.linkManualPort,
keyboardType: TextInputType.number,
last: true,
),
if (_invalid) ...[
const SizedBox(height: 12),
Text(
l10n.linkErrorInvalidAddress,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.error,
),
),
],
],
),
actions: [
AppDialogAction(
onPressed: () => Navigator.of(context).pop(),
child: Text(l10n.dialogCancel),
),
AppDialogAction(
filled: true,
onPressed: _submit,
child: Text(l10n.linkContinue),
),
],
);
}
}
/// Confirms forgetting [name]. Pops whether its music should leave Library
/// too, or null when cancelled.
class LinkForgetDialog extends StatefulWidget {
const LinkForgetDialog({super.key, required this.name});
final String name;
@override
State<LinkForgetDialog> createState() => _LinkForgetDialogState();
}
class _LinkForgetDialogState extends State<LinkForgetDialog> {
var _removeLibrary = true;
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final error = Theme.of(context).colorScheme.error;
return AppAlertDialog(
title: Text(l10n.linkForgetTitle(widget.name)),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(l10n.linkForgetMessage),
const SizedBox(height: 12),
MergeSemantics(
child: Row(
children: [
Expanded(child: Text(l10n.linkForgetRemoveLibrary)),
const SizedBox(width: 12),
AppSwitch(
value: _removeLibrary,
semanticLabel: l10n.linkForgetRemoveLibrary,
onChanged: (value) => setState(() => _removeLibrary = value),
),
],
),
),
],
),
actions: [
AppDialogAction(
onPressed: () => Navigator.of(context).pop(),
child: Text(l10n.dialogCancel),
),
AppDialogAction(
isDestructive: true,
style: TextButton.styleFrom(foregroundColor: error),
onPressed: () => Navigator.of(context).pop(_removeLibrary),
child: Text(l10n.linkForget),
),
],
);
}
}
@@ -0,0 +1,417 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mornye/l10n/l10n.dart';
import 'package:mornye/screens/settings/link_pairing_dialogs.dart';
import 'package:mornye/services/link/client/link_client_controller.dart';
import 'package:mornye/services/link/client/link_client_discovery.dart';
import 'package:mornye/services/link/client/link_client_pairing.dart';
import 'package:mornye/services/link/client/link_client_session.dart';
import 'package:mornye/services/link/link_client_api.dart';
import 'package:mornye/services/local_network_access.dart';
import 'package:mornye/theme/mornye_theme.dart';
import 'package:mornye/utils/nav_bar_inset.dart';
import 'package:mornye/widgets/app_action_button.dart';
import 'package:mornye/widgets/app_alert_dialog.dart';
import 'package:mornye/widgets/app_progress_indicator.dart';
import 'package:mornye/widgets/app_sliver_header.dart';
import 'package:mornye/widgets/expressive_icon_button.dart';
import 'package:mornye/widgets/settings_group.dart';
/// Mornye on your computer: paired computers with their connection, the
/// computers found on the network, and pairing.
class LinkSettingsPage extends ConsumerStatefulWidget {
const LinkSettingsPage({super.key});
@override
ConsumerState<LinkSettingsPage> createState() => _LinkSettingsPageState();
}
class _LinkSettingsPageState extends ConsumerState<LinkSettingsPage> {
late final VoidCallback _releaseDiscovery;
var _busy = false;
LinkClientController get _controller =>
ref.read(linkClientControllerProvider.notifier);
@override
void initState() {
super.initState();
_releaseDiscovery = _controller.acquireDiscovery();
}
@override
void dispose() {
_releaseDiscovery();
super.dispose();
}
void _showMessage(String message) {
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(message)));
}
Future<void> _showCertificateWarning() => showAppDialog<void>(
context: context,
builder: (context) => AppAlertDialog(
icon: const Icon(Icons.gpp_maybe_outlined),
title: Text(context.l10n.linkErrorCertificateTitle),
content: Text(context.l10n.linkErrorCertificate),
actions: [
AppDialogAction(
filled: true,
onPressed: () => Navigator.of(context).pop(),
child: Text(MaterialLocalizations.of(context).okButtonLabel),
),
],
),
);
/// Reads the computer's `info`, then asks for the PIN and pairs.
Future<void> _pair(
String host,
int port, {
String? expectedFingerprint,
String? name,
}) async {
if (_busy) return;
setState(() => _busy = true);
final LinkPairingTarget target;
try {
target = await _controller.probe(
host,
port,
expectedFingerprint: expectedFingerprint,
);
} on LinkPairingException catch (error) {
if (!mounted) return;
setState(() => _busy = false);
if (error.error == LinkPairingError.certificateMismatch) {
await _showCertificateWarning();
} else {
_showMessage(linkPairingErrorMessage(context.l10n, error.error));
}
return;
}
if (!mounted) return;
setState(() => _busy = false);
final serverName = target.info.name.isNotEmpty
? target.info.name
: name ?? host;
final paired = await showAppDialog<bool>(
context: context,
barrierDismissible: false,
builder: (_) => LinkPinDialog(
serverName: serverName,
shortFingerprint: target.shortFingerprint,
pairingOpen: target.info.pairing,
onSubmit: (pin) async {
try {
await _controller.pair(target, pin);
return null;
} on LinkPairingException catch (error) {
return error.error;
}
},
),
);
if (paired == true && mounted) {
_showMessage(context.l10n.linkPaired(serverName));
}
}
Future<void> _pairDiscovered(LinkDiscoveredServer server) => _pair(
server.host,
server.port,
expectedFingerprint: server.fingerprint,
name: server.name,
);
/// Pairs a known computer again, at its advertised address when the
/// network shows it, else at the saved one.
Future<void> _pairAgain(LinkServerRecord record) {
final found = ref
.read(linkClientControllerProvider)
.discoveredServer(record.serverId);
if (found != null) return _pairDiscovered(found);
final address = Uri.parse(record.address);
return _pair(address.host, address.port, name: record.name);
}
Future<void> _addManually() async {
final address = await showAppDialog<({String host, int port})>(
context: context,
builder: (_) => const LinkManualAddDialog(),
);
if (address == null || !mounted) return;
await _pair(address.host, address.port);
}
Future<void> _forget(LinkServerRecord record) async {
final removeLibrary = await showAppDialog<bool>(
context: context,
builder: (_) => LinkForgetDialog(name: record.name),
);
if (removeLibrary == null || !mounted) return;
await _controller.forget(record.serverId, removeLibrary: removeLibrary);
}
Future<void> _allowLocalNetwork() async {
try {
await _controller.requestLocalNetworkAccess();
} on LocalNetworkPermissionException {
if (mounted) _showMessage(context.l10n.networkErrorLocalPermission);
}
}
String _status(LinkClientState state, LinkServerRecord record) {
final l10n = context.l10n;
if (record.serverId != state.activeServerId) return l10n.linkStateInactive;
return switch (state.connection) {
LinkConnectionState.connected => l10n.linkStateConnected,
LinkConnectionState.connecting => l10n.linkStateConnecting,
LinkConnectionState.disconnected => l10n.linkStateDisconnected,
};
}
List<Widget> _notices(LinkClientState state) {
final l10n = context.l10n;
final active = state.activeServer;
final permissionDenied =
state.discovery == LinkDiscoveryStatus.permissionDenied ||
state.issue == LinkSessionIssue.localNetworkPermission;
return [
if (permissionDenied)
SettingsInfoCard(
tone: SettingsInfoTone.warning,
icon: Icons.wifi_off_rounded,
title: l10n.linkLocalNetworkTitle,
message: l10n.linkLocalNetworkMessage,
action: AppActionButton(
onPressed: _allowLocalNetwork,
icon: const Icon(Icons.lock_open_outlined),
label: Text(l10n.linkLocalNetworkAllow),
tonal: true,
),
)
else if (!state.localNetworkAvailable)
SettingsInfoCard(
tone: SettingsInfoTone.warning,
icon: Icons.wifi_off_rounded,
title: l10n.linkWifiOffTitle,
message: l10n.linkWifiOffMessage,
),
if (active != null &&
state.connection != LinkConnectionState.connected &&
(state.issue == LinkSessionIssue.certificate ||
state.certificateChanged(active)))
SettingsInfoCard(
tone: SettingsInfoTone.error,
icon: Icons.gpp_maybe_outlined,
title: l10n.linkErrorCertificateTitle,
message: l10n.linkIssueCertificate(active.name),
action: AppActionButton(
onPressed: _busy ? null : () => _pairAgain(active),
icon: const Icon(Icons.link),
label: Text(l10n.linkPairAgain),
tonal: true,
),
)
else if (active != null &&
state.connection != LinkConnectionState.connected &&
state.issue == LinkSessionIssue.unauthorized)
SettingsInfoCard(
tone: SettingsInfoTone.error,
icon: Icons.link_off,
message: l10n.linkIssueUnauthorized(active.name),
action: AppActionButton(
onPressed: _busy ? null : () => _pairAgain(active),
icon: const Icon(Icons.link),
label: Text(l10n.linkPairAgain),
tonal: true,
),
)
else if (active != null &&
state.connection != LinkConnectionState.connected &&
state.issue == LinkSessionIssue.incompatible)
SettingsInfoCard(
tone: SettingsInfoTone.warning,
icon: Icons.system_update_outlined,
message: l10n.linkIssueIncompatible(active.name),
),
];
}
Widget _pairedRow(LinkClientState state, LinkServerRecord record) {
final l10n = context.l10n;
final active = record.serverId == state.activeServerId;
final scheme = Theme.of(context).colorScheme;
return SettingsItem(
icon: Icons.computer,
showIconInMornye: true,
iconColor: active && state.connection == LinkConnectionState.connected
? scheme.primary
: null,
title: record.name,
titleTrailing: active && state.servers.length > 1
? Text(
l10n.linkActive,
style: Theme.of(
context,
).textTheme.labelMedium?.copyWith(color: scheme.primary),
)
: null,
subtitle: '${_status(state, record)} · ${Uri.parse(record.address).host}',
onTap: _busy
? null
: active
? (state.connection == LinkConnectionState.disconnected
? _controller.retry
: null)
: () => _controller.setActive(record.serverId),
trailing: _LinkIconAction(
tooltip: l10n.linkForget,
icon: Icons.link_off,
cupertinoIcon: CupertinoIcons.minus_circle,
onPressed: _busy ? null : () => _forget(record),
),
);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final state = ref.watch(linkClientControllerProvider);
final unpaired = state.unpaired;
final searching = state.discovery == LinkDiscoveryStatus.searching;
final theme = Theme.of(context);
final note = theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
);
return Scaffold(
body: CustomScrollView(
slivers: [
AppSliverHeader.page(title: l10n.linkPageTitle),
SliverToBoxAdapter(
child: _LinkInset(
child: Text(l10n.linkPageDescription, style: note),
),
),
if (_busy)
const SliverToBoxAdapter(
child: _LinkInset(child: AppProgressIndicator.linear()),
),
SliverList.list(children: _notices(state)),
if (state.servers.isNotEmpty)
...settingsSectionSlivers(
title: l10n.linkPairedSection,
children: [
for (final record in state.servers) _pairedRow(state, record),
],
),
...settingsSectionSlivers(
title: l10n.linkNearbySection,
children: [
for (final server in unpaired)
SettingsItem(
icon: Icons.computer,
showIconInMornye: true,
title: server.name,
subtitle: server.host,
onTap: _busy ? null : () => _pairDiscovered(server),
),
if (unpaired.isEmpty)
SettingsItem(
icon: Icons.wifi,
showIconInMornye: true,
title: searching
? l10n.linkSearching
: l10n.linkNoneFoundTitle,
subtitle: l10n.linkNoneFound,
trailing: searching
? SizedBox.square(
dimension: 24,
child: context.isMornye
? const CupertinoActivityIndicator()
: const AppProgressIndicator.circular(),
)
: null,
),
],
),
SliverToBoxAdapter(
child: _LinkInset(
child: Align(
alignment: AlignmentDirectional.centerStart,
child: AppActionButton(
onPressed: _busy ? null : _addManually,
icon: const Icon(Icons.add),
label: Text(l10n.linkAddManually),
tonal: true,
),
),
),
),
const NavBarSliverSpacer(),
],
),
);
}
}
/// Lines free content up with the settings groups at any width.
class _LinkInset extends StatelessWidget {
const _LinkInset({required this.child});
final Widget child;
@override
Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) {
final inset = settingsHorizontalInset(constraints.maxWidth);
return Padding(
padding: EdgeInsets.fromLTRB(inset + 8, 8, inset + 8, 8),
child: child,
);
},
);
}
class _LinkIconAction extends StatelessWidget {
const _LinkIconAction({
required this.tooltip,
required this.icon,
required this.cupertinoIcon,
required this.onPressed,
});
final String tooltip;
final IconData icon;
final IconData cupertinoIcon;
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) => context.isMornye
? Tooltip(
message: tooltip,
child: CupertinoButton(
onPressed: onPressed,
padding: const EdgeInsets.all(12),
child: Icon(
cupertinoIcon,
size: 24,
semanticLabel: tooltip,
color: onPressed == null
? Theme.of(context).disabledColor
: Theme.of(context).colorScheme.primary,
),
),
)
: ExpressiveIconButton(
icon: Icon(icon),
tooltip: tooltip,
onPressed: onPressed,
);
}
+18
View File
@@ -19,6 +19,7 @@ import 'package:mornye/screens/settings/extensions_page.dart';
import 'package:mornye/screens/settings/files_settings_page.dart';
import 'package:mornye/screens/settings/keyboard_shortcuts_page.dart';
import 'package:mornye/screens/settings/library_settings_page.dart';
import 'package:mornye/screens/settings/link_settings_page.dart';
import 'package:mornye/screens/network_storage_screen.dart';
import 'package:mornye/screens/settings/log_screen.dart';
import 'package:mornye/screens/settings/lyrics_settings_page.dart';
@@ -247,6 +248,23 @@ class _SettingsTabState extends ConsumerState<SettingsTab> {
],
pageBuilder: () => const NetworkStorageScreen(),
),
if (Platform.isAndroid || Platform.isIOS)
_Destination(
icon: Icons.computer,
iconColor: Colors.deepPurple,
title: l10n.linkSettingsTitle,
subtitle: l10n.linkSettingsSubtitle,
keywords: const [
'computer',
'desktop',
'pc',
'mac',
'pair',
'link',
'komputer',
],
pageBuilder: () => const LinkSettingsPage(),
),
_Destination(
icon: Icons.sell_outlined,
iconColor: Colors.amber,
@@ -0,0 +1,66 @@
import 'dart:async';
import 'package:bonsoir/bonsoir.dart';
import 'package:mornye/services/link/client/link_client_discovery.dart';
import 'package:mornye/services/link/link_protocol.dart';
/// [LinkServiceBrowser] on Bonsoir (Android NSD, Apple Bonjour). Found
/// services are resolved right away, since the list shows their addresses.
class BonsoirLinkServiceBrowser implements LinkServiceBrowser {
BonsoirDiscovery? _discovery;
StreamSubscription<BonsoirDiscoveryEvent>? _subscription;
StreamController<LinkServiceEvent>? _events;
@override
Future<Stream<LinkServiceEvent>> start() async {
await stop();
final discovery = _discovery = BonsoirDiscovery(
type: linkServiceType,
printLogs: false,
);
_events = StreamController<LinkServiceEvent>();
await discovery.initialize();
_subscription = discovery.eventStream?.listen((event) {
switch (event) {
case BonsoirDiscoveryServiceFoundEvent(:final service):
unawaited(
service
.resolve(discovery.serviceResolver)
.catchError((Object _) {}),
);
case BonsoirDiscoveryServiceResolvedEvent(:final service) ||
BonsoirDiscoveryServiceUpdatedEvent(:final service):
_events?.add(
LinkServiceResolved(
name: service.name,
port: service.port,
addresses: service.hostAddresses,
hostname: service.hostname,
attributes: service.attributes,
),
);
case BonsoirDiscoveryServiceLostEvent(:final service):
_events?.add(LinkServiceLost(service.name));
default:
break;
}
}, onError: (Object error) => _events?.addError(error));
await discovery.start();
return _events!.stream;
}
@override
Future<void> stop() async {
final discovery = _discovery;
_discovery = null;
final cancelling = _subscription?.cancel();
_subscription = null;
// Nobody may listen any more, so the close is not awaited.
unawaited(_events?.close());
_events = null;
await cancelling;
if (discovery != null && discovery.isReady && !discovery.isStopped) {
await discovery.stop();
}
}
}
@@ -0,0 +1,620 @@
import 'dart:async';
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mornye/constants/app_info.dart';
import 'package:mornye/services/link/client/link_client_bonsoir.dart';
import 'package:mornye/services/link/client/link_client_discovery.dart';
import 'package:mornye/services/link/client/link_client_http.dart';
import 'package:mornye/services/link/client/link_client_library.dart';
import 'package:mornye/services/link/client/link_client_pairing.dart';
import 'package:mornye/services/link/client/link_client_session.dart';
import 'package:mornye/services/link/client/link_client_store.dart';
import 'package:mornye/services/link/link_client_api.dart';
import 'package:mornye/services/link/link_protocol.dart';
import 'package:mornye/services/local_network_access.dart';
import 'package:mornye/services/network_storage_service.dart';
import 'package:mornye/utils/logger.dart';
final _log = AppLogger('LinkClient');
/// Whether this device runs the phone side of Mornye Link.
final linkClientSupportedProvider = Provider<bool>(
(ref) => Platform.isAndroid || Platform.isIOS,
);
/// Device inputs of the client, replaced in tests.
class LinkClientEnvironment {
const LinkClientEnvironment({
required this.deviceName,
required this.platform,
required this.appVersion,
required this.createBrowser,
required this.createSession,
required this.ensureLocalNetwork,
required this.onLocalNetwork,
});
/// The name desktops list this phone under.
final Future<String> Function() deviceName;
/// `android` or `ios`.
final String platform;
final String appVersion;
final LinkServiceBrowser Function() createBrowser;
final LinkSession Function(
LinkServerRecord server,
String apiKey,
LinkDeviceIdentity device,
)
createSession;
/// Asks for local network access where the OS gates it; throws
/// [LocalNetworkPermissionException] when refused.
final Future<void> Function() ensureLocalNetwork;
/// Whether Wi-Fi or Ethernet is connected.
final Future<bool> Function() onLocalNetwork;
factory LinkClientEnvironment.device() => LinkClientEnvironment(
deviceName: _deviceName,
platform: Platform.isIOS ? 'ios' : 'android',
appVersion: AppInfo.version,
createBrowser: BonsoirLinkServiceBrowser.new,
createSession: (server, apiKey, device) =>
LinkClientSession(server: server, apiKey: apiKey, device: device),
ensureLocalNetwork: LocalNetworkAccess.instance.ensureGranted,
onLocalNetwork: _onLocalNetwork,
);
static Future<String> _deviceName() async {
try {
final info = DeviceInfoPlugin();
if (Platform.isAndroid) {
final android = await info.androidInfo;
final name = android.name.trim();
return name.isNotEmpty ? name : android.model;
}
if (Platform.isIOS) {
final ios = await info.iosInfo;
return ios.name.trim().isNotEmpty ? ios.name.trim() : ios.model;
}
} catch (error) {
_log.w('Reading the device name failed: $error');
}
return Platform.isIOS ? 'iPhone' : 'Android';
}
static Future<bool> _onLocalNetwork() async {
try {
final results = await Connectivity().checkConnectivity();
return results.contains(ConnectivityResult.wifi) ||
results.contains(ConnectivityResult.ethernet);
} catch (_) {
// Unknown: do not warn about something we could not check.
return true;
}
}
}
final linkClientEnvironmentProvider = Provider<LinkClientEnvironment>(
(ref) => LinkClientEnvironment.device(),
);
final linkClientStoreProvider = Provider<LinkClientStore>(
(ref) => LinkClientStore(),
);
final linkPairingApiProvider = Provider<LinkPairingApi>(
(ref) => LinkPairingClient(),
);
final linkLibraryBridgeProvider = Provider<LinkLibraryBridge>(
LinkNetworkLibraryBridge.new,
);
@immutable
class LinkClientState {
const LinkClientState({
this.loaded = false,
this.servers = const [],
this.activeServerId,
this.connection = LinkConnectionState.disconnected,
this.issue,
this.discovered = const [],
this.discovery = LinkDiscoveryStatus.idle,
this.localNetworkAvailable = true,
});
final bool loaded;
/// Paired desktops, in pairing order.
final List<LinkServerRecord> servers;
/// The desktop [linkActiveClientProvider] talks to.
final String? activeServerId;
/// The active session's connection.
final LinkConnectionState connection;
/// Why the active session last failed, cleared once it connects.
final LinkSessionIssue? issue;
/// Desktops on the network while discovery runs.
final List<LinkDiscoveredServer> discovered;
final LinkDiscoveryStatus discovery;
/// False when neither Wi-Fi nor Ethernet is connected.
final bool localNetworkAvailable;
LinkServerRecord? get activeServer =>
servers.where((s) => s.serverId == activeServerId).firstOrNull;
/// Discovered desktops this phone is not paired with.
List<LinkDiscoveredServer> get unpaired => [
for (final server in discovered)
if (!servers.any((s) => s.serverId == server.serverId)) server,
];
LinkDiscoveredServer? discoveredServer(String serverId) =>
discovered.where((s) => s.serverId == serverId).firstOrNull;
/// Whether discovery sees [server] with another certificate than the one
/// it was paired with.
bool certificateChanged(LinkServerRecord server) {
final found = discoveredServer(server.serverId);
return found != null && found.fingerprint != server.fingerprint;
}
LinkClientState copyWith({
bool? loaded,
List<LinkServerRecord>? servers,
String? activeServerId,
bool clearActiveServer = false,
LinkConnectionState? connection,
LinkSessionIssue? issue,
bool clearIssue = false,
List<LinkDiscoveredServer>? discovered,
LinkDiscoveryStatus? discovery,
bool? localNetworkAvailable,
}) => LinkClientState(
loaded: loaded ?? this.loaded,
servers: servers ?? this.servers,
activeServerId: clearActiveServer
? null
: activeServerId ?? this.activeServerId,
connection: connection ?? this.connection,
issue: clearIssue ? null : issue ?? this.issue,
discovered: discovered ?? this.discovered,
discovery: discovery ?? this.discovery,
localNetworkAvailable: localNetworkAvailable ?? this.localNetworkAvailable,
);
}
/// The phone side of Mornye Link: paired desktops, discovery, pairing and
/// the active session it publishes through [linkActiveClientProvider].
/// The app root keeps it alive on phones; it does nothing elsewhere.
class LinkClientController extends Notifier<LinkClientState> {
/// How long `catalog.changed` bursts settle before a rescan.
static const rescanDelay = Duration(seconds: 2);
LinkSession? _session;
StreamSubscription<LinkConnectionState>? _stateSubscription;
StreamSubscription<Map<String, dynamic>>? _messageSubscription;
LinkDiscovery? _discovery;
AppLifecycleListener? _lifecycle;
Timer? _rescan;
Future<void> _mutation = Future.value();
Future<void>? _loading;
LinkDeviceIdentity? _device;
var _foreground = true;
var _discoveryHolds = 0;
var _discoveryBlocked = false;
/// True until a supported build starts the client and after disposal, so
/// every entry point is inert on desktops.
var _disposed = true;
LinkClientEnvironment get _environment =>
ref.read(linkClientEnvironmentProvider);
LinkClientStore get _store => ref.read(linkClientStoreProvider);
LinkLibraryBridge get _library => ref.read(linkLibraryBridgeProvider);
/// The active session, as [linkActiveClientProvider] publishes it.
LinkSession? get session => _session;
/// Completes once paired desktops are loaded and the session started.
Future<void> get ready => _loading ?? Future.value();
@override
LinkClientState build() {
if (!ref.watch(linkClientSupportedProvider)) {
return const LinkClientState(loaded: true);
}
_disposed = false;
_lifecycle = AppLifecycleListener(onStateChange: _onLifecycle);
ref.onDispose(_dispose);
_loading = Future<void>.microtask(
() => _serial(_load).catchError(
(Object error, StackTrace stack) =>
_log.e('Loading paired computers failed', error, stack),
),
);
return const LinkClientState();
}
Future<T> _serial<T>(Future<T> Function() action) {
final result = _mutation.then((_) => action());
_mutation = result.then<void>((_) {}, onError: (Object _) {});
return result;
}
Future<void> _load() async {
final store = _store;
final servers = await store.servers();
var active = await store.activeServerId();
if (_disposed) return;
if (!servers.any((s) => s.serverId == active)) {
active = servers.firstOrNull?.serverId;
}
state = state.copyWith(
loaded: true,
servers: servers,
activeServerId: active,
clearActiveServer: active == null,
);
await _restartSession();
}
Future<LinkDeviceIdentity> _identity() async {
final known = _device;
if (known != null) return known;
final environment = _environment;
final deviceId = await _store.deviceId();
final name = await environment.deviceName();
return _device = LinkDeviceIdentity(
deviceId: deviceId,
name: name,
platform: environment.platform,
appVersion: environment.appVersion,
);
}
/// Replaces the session with one for the active desktop. Runs serialized.
Future<void> _restartSession() async {
final previous = _session;
_session = null;
await _stateSubscription?.cancel();
await _messageSubscription?.cancel();
_stateSubscription = null;
_messageSubscription = null;
_rescan?.cancel();
final record = state.activeServer;
LinkSession? next;
LinkSessionIssue? issue;
if (record != null) {
final connection = await _library.connection(record.connectionId);
if (_disposed) {
await previous?.dispose();
return;
}
if (connection == null || connection.apiKey.isEmpty) {
// The network connection was removed elsewhere: pair again.
issue = LinkSessionIssue.unauthorized;
} else {
next = _environment.createSession(
record,
connection.apiKey,
await _identity(),
);
}
}
if (_disposed) {
await previous?.dispose();
await next?.dispose();
return;
}
_session = next;
if (next != null) {
final session = next;
_stateSubscription = session.connectionStates.listen(
(_) => _onConnection(session),
);
_messageSubscription = session.messages.listen(
(message) => _onMessage(session, message),
);
}
ref.read(linkActiveClientProvider.notifier).set(next);
state = state.copyWith(
connection: next?.connectionState ?? LinkConnectionState.disconnected,
issue: issue,
clearIssue: issue == null,
);
await previous?.dispose();
if (next != null) {
if (!_foreground) next.pause();
next.start();
}
_updateDiscovery();
}
void _onConnection(LinkSession session) {
if (_disposed || !identical(session, _session)) return;
state = state.copyWith(
connection: session.connectionState,
issue: session.issue,
clearIssue: session.issue == null,
);
_updateDiscovery();
}
void _onMessage(LinkSession session, Map<String, dynamic> message) {
if (_disposed || !identical(session, _session)) return;
if (message['type'] != LinkMessageTypes.catalogChanged) return;
final connectionId = session.server.connectionId;
_rescan?.cancel();
_rescan = Timer(rescanDelay, () {
_rescan = null;
unawaited(
_library
.rescan(connectionId)
.catchError(
(Object error) =>
_log.w('Rescanning the computer failed: $error'),
),
);
});
}
void _onLifecycle(AppLifecycleState lifecycle) {
// Inactive covers the iOS control centre and app switcher; keep going.
if (lifecycle == AppLifecycleState.inactive) return;
final foreground = lifecycle == AppLifecycleState.resumed;
if (foreground == _foreground || _disposed) return;
_foreground = foreground;
if (foreground) {
_session?.resume();
unawaited(refreshLocalNetwork());
} else {
_session?.pause();
}
_updateDiscovery();
}
/// Keeps discovery running while the returned callback is not called, for
/// the settings page. Discovery also runs on its own while the active
/// desktop is unreachable, to follow it to a new address.
///
/// Pages call it from `initState` and release it from `dispose`, so the
/// state changes it causes wait for a microtask, after the frame.
VoidCallback acquireDiscovery() {
_discoveryHolds++;
_discoveryBlocked = false;
scheduleMicrotask(_updateDiscovery);
unawaited(Future<void>.microtask(refreshLocalNetwork));
var released = false;
return () {
if (released) return;
released = true;
_discoveryHolds--;
scheduleMicrotask(_updateDiscovery);
};
}
void _updateDiscovery() {
if (_disposed) return;
final wanted =
_foreground &&
!_discoveryBlocked &&
(_discoveryHolds > 0 ||
(_session != null &&
state.connection != LinkConnectionState.connected));
final discovery = _discovery ??= LinkDiscovery(
createBrowser: _environment.createBrowser,
ensureAccess: _environment.ensureLocalNetwork,
onChanged: _onDiscoveryChanged,
);
if (wanted && discovery.status != LinkDiscoveryStatus.searching) {
unawaited(discovery.start());
} else if (!wanted && discovery.status == LinkDiscoveryStatus.searching) {
unawaited(discovery.stop());
}
}
void _onDiscoveryChanged() {
final discovery = _discovery;
if (_disposed || discovery == null) return;
final before = {for (final s in state.discovered) s.serverId};
final found = discovery.servers;
if (discovery.status == LinkDiscoveryStatus.permissionDenied) {
// Do not ask again on every reconnect; the page offers a button.
_discoveryBlocked = true;
}
state = state.copyWith(discovered: found, discovery: discovery.status);
for (final server in found) {
final record = state.servers
.where((s) => s.serverId == server.serverId)
.firstOrNull;
// Another certificate under a known id is not followed anywhere.
if (record == null || record.fingerprint != server.fingerprint) continue;
if (record.address != server.address) {
unawaited(_serial(() => _move(record.serverId, server.address)));
} else if (!before.contains(server.serverId) &&
record.serverId == state.activeServerId) {
_session?.reconnectNow();
}
}
}
Future<void> _move(String serverId, String address) async {
final record = state.servers
.where((s) => s.serverId == serverId)
.firstOrNull;
if (record == null || record.address == address || _disposed) return;
_log.i('Computer ${record.name} moved to a new address');
final servers = await _store.updateAddress(serverId, address);
await _library.updateAddress(record.connectionId, address);
if (_disposed) return;
state = state.copyWith(servers: servers);
final updated = servers.where((s) => s.serverId == serverId).firstOrNull;
final session = _session;
if (updated != null &&
session != null &&
serverId == state.activeServerId) {
session.updateServer(updated);
}
}
/// Rechecks Wi-Fi for the page's warning.
Future<void> refreshLocalNetwork() async {
if (_disposed) return;
final available = await _environment.onLocalNetwork();
if (_disposed || available == state.localNetworkAvailable) return;
state = state.copyWith(localNetworkAvailable: available);
}
/// Asks for local network access again, then retries discovery and the
/// session. Throws [LocalNetworkPermissionException] when refused.
Future<void> requestLocalNetworkAccess() async {
if (_disposed) return;
await _environment.ensureLocalNetwork();
if (_disposed) return;
_discoveryBlocked = false;
_updateDiscovery();
_session?.reconnectNow();
}
/// Retries the active desktop now.
void retry() => _session?.reconnectNow();
/// Reads a desktop's `info` before asking for its PIN.
Future<LinkPairingTarget> probe(
String host,
int port, {
String? expectedFingerprint,
}) {
final address = linkServerAddress(host, port);
if (address == null) {
return Future.error(
const LinkPairingException(LinkPairingError.invalidAddress),
);
}
return ref
.read(linkPairingApiProvider)
.probe(address, expectedFingerprint: expectedFingerprint);
}
/// Pairs with [target] using [pin]. On success the desktop is saved as a
/// Subsonic network connection, added to Library and scanned; re-pairing
/// replaces the stored key. Throws [LinkPairingException].
Future<LinkServerRecord> pair(LinkPairingTarget target, String pin) async {
final result = await ref
.read(linkPairingApiProvider)
.pair(target, pin: pin, device: await _identity());
final (record, connection) = await _serial(() async {
final existing = state.servers
.where((s) => s.serverId == result.serverId)
.firstOrNull;
final name = result.name.isNotEmpty
? result.name
: Uri.parse(target.address).host;
final connection = NetworkConnection(
id: existing?.connectionId ?? NetworkStorageService.newId(),
name: name,
protocol: NetworkProtocol.subsonic,
address: target.address,
subsonicAuth: SubsonicAuth.apiKey,
apiKey: result.apiKey,
trustedCertificateSha256: result.fingerprint,
);
await _library.saveConnection(connection);
final record = LinkServerRecord(
serverId: result.serverId,
name: name,
connectionId: connection.id,
address: target.address,
fingerprint: result.fingerprint,
);
final servers = await _store.upsert(record);
var active = state.activeServerId;
if (active == null || !servers.any((s) => s.serverId == active)) {
active = record.serverId;
await _store.setActiveServerId(active);
}
if (!_disposed) {
state = state.copyWith(servers: servers, activeServerId: active);
if (active == record.serverId) await _restartSession();
}
return (record, connection);
});
unawaited(
_library
.addLibrarySource(connection)
.catchError(
(Object error) =>
_log.w('Adding the computer to Library failed: $error'),
),
);
return record;
}
/// Makes [serverId] the desktop features talk to.
Future<void> setActive(String serverId) => _serial(() async {
if (state.activeServerId == serverId ||
!state.servers.any((s) => s.serverId == serverId)) {
return;
}
await _store.setActiveServerId(serverId);
if (_disposed) return;
state = state.copyWith(activeServerId: serverId);
await _restartSession();
});
/// Forgets a paired desktop. With [removeLibrary] its network connection
/// and Library source go too; otherwise its music stays browsable.
Future<void> forget(String serverId, {required bool removeLibrary}) =>
_serial(() async {
final record = state.servers
.where((s) => s.serverId == serverId)
.firstOrNull;
if (record == null) return;
final servers = await _store.remove(serverId);
final wasActive = state.activeServerId == serverId;
final active = wasActive
? servers.firstOrNull?.serverId
: state.activeServerId;
if (wasActive) await _store.setActiveServerId(active);
if (!_disposed) {
state = state.copyWith(
servers: servers,
activeServerId: active,
clearActiveServer: active == null,
);
if (wasActive) await _restartSession();
}
if (removeLibrary) await _library.removeConnection(record.connectionId);
});
void _dispose() {
_disposed = true;
_lifecycle?.dispose();
_lifecycle = null;
_rescan?.cancel();
unawaited(_stateSubscription?.cancel());
unawaited(_messageSubscription?.cancel());
final discovery = _discovery;
_discovery = null;
unawaited(discovery?.stop());
final session = _session;
_session = null;
unawaited(session?.dispose());
}
}
final linkClientControllerProvider =
NotifierProvider<LinkClientController, LinkClientState>(
LinkClientController.new,
);
@@ -0,0 +1,262 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:mornye/services/link/link_protocol.dart';
import 'package:mornye/services/local_network_access.dart';
import 'package:mornye/utils/logger.dart';
final _log = AppLogger('LinkDiscovery');
/// One mDNS event for [linkServiceType], independent of the plugin.
sealed class LinkServiceEvent {
const LinkServiceEvent(this.name);
/// The mDNS instance name, which the desktop sets to its server name.
final String name;
}
/// A service was resolved, or its record changed.
class LinkServiceResolved extends LinkServiceEvent {
const LinkServiceResolved({
required String name,
required this.port,
this.addresses = const [],
this.hostname,
this.attributes = const {},
}) : super(name);
final int port;
/// Addresses as the platform reports them, IPv4 or IPv6.
final List<String> addresses;
/// The SRV target, usually `<name>.local`, when the platform reports it.
final String? hostname;
/// TXT record: `v`, `id` and `fp`.
final Map<String, String> attributes;
}
/// A service left the network.
class LinkServiceLost extends LinkServiceEvent {
const LinkServiceLost(super.name);
}
/// Browses the local network for desktops. The app uses Bonsoir; tests feed
/// events by hand.
abstract interface class LinkServiceBrowser {
/// Starts browsing; resolved and lost services arrive until [stop].
Future<Stream<LinkServiceEvent>> start();
Future<void> stop();
}
/// A desktop found on the local network.
@immutable
class LinkDiscoveredServer {
const LinkDiscoveredServer({
required this.serviceName,
required this.serverId,
required this.name,
required this.host,
required this.port,
required this.fingerprint,
});
/// The mDNS instance name, which identifies the service in lost events.
final String serviceName;
final String serverId;
final String name;
final String host;
final int port;
/// The certificate fingerprint the desktop advertises (TXT `fp`). Pairing
/// still checks it against the certificate it actually sees.
final String fingerprint;
/// `https://host:port`, the form of [LinkServerRecord.address].
String get address => Uri(scheme: 'https', host: host, port: port).toString();
@override
bool operator ==(Object other) =>
other is LinkDiscoveredServer &&
other.serviceName == serviceName &&
other.serverId == serverId &&
other.name == name &&
other.host == host &&
other.port == port &&
other.fingerprint == fingerprint;
@override
int get hashCode =>
Object.hash(serviceName, serverId, name, host, port, fingerprint);
@override
String toString() => 'LinkDiscoveredServer($name, $serverId, $address)';
}
final _fingerprintPattern = RegExp(r'^[0-9a-f]{64}$');
/// The desktop behind a resolved service, or null when it is not a Mornye
/// Link server of this protocol or has no usable address.
LinkDiscoveredServer? linkDiscoveredServerFrom(LinkServiceResolved service) {
final attributes = service.attributes;
if (attributes['v']?.trim() != '$linkProtocolVersion') return null;
final serverId = attributes['id']?.trim() ?? '';
final fingerprint = attributes['fp']?.trim().toLowerCase() ?? '';
if (serverId.isEmpty || !_fingerprintPattern.hasMatch(fingerprint)) {
return null;
}
if (service.port < 1 || service.port > 65535) return null;
final host = linkPreferredHost(service.addresses, service.hostname);
if (host == null) return null;
final name = service.name.trim();
return LinkDiscoveredServer(
serviceName: service.name,
serverId: serverId,
name: name.isEmpty ? host : name,
host: host,
port: service.port,
fingerprint: fingerprint,
);
}
/// The address to reach a desktop at: IPv4 first, since it needs no zone,
/// then a routable IPv6 address, then the mDNS host name. Link-local IPv6
/// is skipped because a URL cannot carry its interface reliably.
@visibleForTesting
String? linkPreferredHost(List<String> addresses, String? hostname) {
final parsed = [
for (final address in addresses)
?InternetAddress.tryParse(address.split('%').first.trim()),
];
for (final address in parsed) {
if (address.type == InternetAddressType.IPv4 && !address.isLoopback) {
return address.address;
}
}
for (final address in parsed) {
if (address.type == InternetAddressType.IPv6 &&
!address.isLoopback &&
!address.isLinkLocal) {
return address.address;
}
}
final name = hostname?.trim().replaceFirst(RegExp(r'\.$'), '') ?? '';
return name.isEmpty ? null : name;
}
enum LinkDiscoveryStatus { idle, searching, permissionDenied, failed }
/// Keeps the list of desktops on the network while browsing runs.
class LinkDiscovery {
LinkDiscovery({
required LinkServiceBrowser Function() createBrowser,
required void Function() onChanged,
Future<void> Function()? ensureAccess,
}) : _createBrowser = createBrowser,
_onChanged = onChanged,
_ensureAccess =
ensureAccess ?? LocalNetworkAccess.instance.ensureGranted;
final LinkServiceBrowser Function() _createBrowser;
final void Function() _onChanged;
final Future<void> Function() _ensureAccess;
final _byService = <String, LinkDiscoveredServer>{};
LinkServiceBrowser? _browser;
StreamSubscription<LinkServiceEvent>? _subscription;
var _generation = 0;
var _status = LinkDiscoveryStatus.idle;
LinkDiscoveryStatus get status => _status;
/// Whether browsing was asked for and has not stopped or failed.
bool get running => _status == LinkDiscoveryStatus.searching;
/// Desktops on the network, one per server id, sorted by name.
List<LinkDiscoveredServer> get servers {
final byServer = <String, LinkDiscoveredServer>{};
for (final server in _byService.values) {
byServer[server.serverId] = server;
}
return byServer.values.toList()
..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
}
Future<void> start() async {
if (running) return;
final generation = ++_generation;
_status = LinkDiscoveryStatus.searching;
_onChanged();
try {
await _ensureAccess();
if (generation != _generation) return;
final browser = _browser = _createBrowser();
final events = await browser.start();
if (generation != _generation) {
await browser.stop();
return;
}
_subscription = events.listen(
(event) => _handle(generation, event),
onError: (Object error) => _fail(generation, error),
);
} catch (error) {
_fail(generation, error);
}
}
Future<void> stop() async {
_generation++;
final subscription = _subscription;
final browser = _browser;
_subscription = null;
_browser = null;
final changed =
_byService.isNotEmpty || _status == LinkDiscoveryStatus.searching;
_byService.clear();
if (_status == LinkDiscoveryStatus.searching) {
_status = LinkDiscoveryStatus.idle;
}
if (changed) _onChanged();
await subscription?.cancel();
try {
await browser?.stop();
} catch (error) {
_log.w('Stopping discovery failed: $error');
}
}
void _handle(int generation, LinkServiceEvent event) {
if (generation != _generation) return;
switch (event) {
case LinkServiceResolved():
final server = linkDiscoveredServerFrom(event);
// An update without addresses keeps the last resolved entry.
if (server == null || _byService[event.name] == server) return;
_byService[event.name] = server;
case LinkServiceLost():
if (_byService.remove(event.name) == null) return;
}
_onChanged();
}
void _fail(int generation, Object error) {
if (generation != _generation) return;
_generation++;
final browser = _browser;
_browser = null;
unawaited(_subscription?.cancel());
_subscription = null;
unawaited(browser?.stop().catchError((Object _) {}));
_byService.clear();
_status = error is LocalNetworkPermissionException
? LinkDiscoveryStatus.permissionDenied
: LinkDiscoveryStatus.failed;
if (_status == LinkDiscoveryStatus.failed) {
_log.w('Discovery failed: $error');
}
_onChanged();
}
}
@@ -0,0 +1,205 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'package:mornye/services/link/link_protocol.dart';
import 'package:mornye/services/local_network_access.dart';
/// Requests to the desktop give up after this long.
const linkRequestTimeout = Duration(seconds: 20);
/// Response bodies above this size are refused (the server's request limit).
const _maxBodyBytes = 8 * 1024 * 1024;
/// Error codes the phone adds to the contract's `invalid`, `not_found`,
/// `unavailable` and `timeout` when the failure happens on the way.
abstract final class LinkClientErrors {
static const unauthorized = 'unauthorized';
static const certificate = 'certificate';
static const unavailable = 'unavailable';
static const timeout = 'timeout';
static const invalid = 'invalid';
static const localNetworkPermission = 'local_network_permission';
}
/// The certificate fingerprint as the contract and the network storage trust
/// store write it: lowercase hex SHA-256 of the DER bytes.
String linkCertificateFingerprint(X509Certificate certificate) =>
sha256.convert(certificate.der).toString();
/// `https://host:port` for a desktop, or null when [host] or [port] cannot
/// form one. IPv6 literals are bracketed; a scheme or path is refused.
Uri? linkServerAddress(String host, int port) {
final trimmed = host.trim().replaceAll(RegExp(r'^\[|\]$'), '');
if (trimmed.isEmpty ||
port < 1 ||
port > 65535 ||
trimmed.contains('/') ||
trimmed.contains('@') ||
trimmed.contains(' ') ||
(trimmed.contains(':') && InternetAddress.tryParse(trimmed) == null)) {
return null;
}
try {
return Uri(scheme: 'https', host: trimmed, port: port);
} on FormatException {
return null;
}
}
/// An [HttpClient] that trusts exactly the certificate whose fingerprint is
/// [fingerprint]. It loads no CA roots, so every handshake reaches the
/// callback and nothing but the pinned certificate passes, not even a
/// publicly trusted one.
HttpClient linkPinnedHttpClient(String fingerprint) {
final pin = fingerprint.toLowerCase();
return HttpClient(context: SecurityContext(withTrustedRoots: false))
..connectionTimeout = linkRequestTimeout
..idleTimeout = const Duration(seconds: 15)
..badCertificateCallback = (certificate, _, _) =>
linkCertificateFingerprint(certificate) == pin;
}
/// An [HttpClient] for first contact with an unpaired desktop. It accepts the
/// certificate presented by [target]'s host and port, and no other host, so
/// the caller can read the fingerprint from the response
/// ([LinkHttpResponse.certificateFingerprint]) and compare it with what the
/// desktop claims before trusting anything.
HttpClient linkFirstContactHttpClient(Uri target) =>
HttpClient(context: SecurityContext(withTrustedRoots: false))
..connectionTimeout = linkRequestTimeout
..badCertificateCallback = (_, host, port) =>
host == target.host && port == target.port;
class LinkHttpResponse {
const LinkHttpResponse({
required this.statusCode,
this.body,
this.certificateFingerprint,
});
final int statusCode;
/// The decoded JSON body, or null when it was empty or not JSON.
final Object? body;
/// The fingerprint of the certificate the server presented, or null over
/// plain HTTP.
final String? certificateFingerprint;
bool get ok => statusCode >= 200 && statusCode < 300;
}
/// Sends one JSON request and reads the whole JSON answer.
Future<LinkHttpResponse> linkHttpSend(
HttpClient client,
String method,
Uri uri, {
Map<String, String> headers = const {},
Map<String, dynamic>? json,
Duration timeout = linkRequestTimeout,
}) async {
var expired = false;
final request = await client
.openUrl(method, uri)
.then((request) {
if (expired) request.abort();
return request;
})
.timeout(
timeout,
onTimeout: () {
expired = true;
throw TimeoutException('The computer did not answer in time');
},
);
final HttpClientResponse response;
try {
request.followRedirects = false;
request.headers.set(HttpHeaders.acceptHeader, 'application/json');
headers.forEach(request.headers.set);
if (json != null) {
final bytes = utf8.encode(jsonEncode(json));
request.headers.contentType = ContentType.json;
request.contentLength = bytes.length;
request.add(bytes);
}
response = await request.close().timeout(timeout);
} catch (_) {
request.abort();
rethrow;
}
final certificate = response.certificate;
final bytes = BytesBuilder(copy: false);
await for (final chunk in response.timeout(timeout)) {
if (bytes.length + chunk.length > _maxBodyBytes) {
throw const HttpException('The computer sent too much data');
}
bytes.add(chunk);
}
Object? body;
if (bytes.isNotEmpty) {
try {
body = jsonDecode(utf8.decode(bytes.takeBytes()));
} on FormatException {
body = null;
}
}
return LinkHttpResponse(
statusCode: response.statusCode,
body: body,
certificateFingerprint: certificate == null
? null
: linkCertificateFingerprint(certificate),
);
}
/// The [LinkException] for a failed response: the body's
/// `{"error","message"}` when present, else a code from the status.
LinkException linkResponseException(LinkHttpResponse response) {
final body = response.body;
if (body is Map && body['error'] is String) {
final message = body['message'];
return LinkException(
body['error'] as String,
message is String ? message : '',
);
}
final status = response.statusCode;
return LinkException(switch (status) {
400 => LinkClientErrors.invalid,
401 => LinkClientErrors.unauthorized,
404 => 'not_found',
503 => LinkClientErrors.unavailable,
504 => LinkClientErrors.timeout,
_ => 'http_$status',
}, 'HTTP $status');
}
/// The [LinkException] for a transport failure. Messages stay generic, so no
/// address or credential leaks into logs or the UI.
LinkException linkTransportException(Object error) => switch (error) {
LinkException() => error,
TimeoutException() => const LinkException(
LinkClientErrors.timeout,
'The computer did not answer in time',
),
LocalNetworkPermissionException() => const LinkException(
LinkClientErrors.localNetworkPermission,
'Local network access is not allowed',
),
TlsException() => const LinkException(
LinkClientErrors.certificate,
'The computer presented another certificate',
),
WebSocketException(httpStatusCode: 401) => const LinkException(
LinkClientErrors.unauthorized,
'The computer no longer accepts this phone',
),
_ => const LinkException(
LinkClientErrors.unavailable,
'The computer could not be reached',
),
};
@@ -0,0 +1,149 @@
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mornye/providers/local_library_provider.dart';
import 'package:mornye/providers/settings_provider.dart';
import 'package:mornye/services/library_database.dart';
import 'package:mornye/services/network_storage_service.dart';
import 'package:mornye/utils/logger.dart';
final _log = AppLogger('LinkLibrary');
/// Where a paired desktop meets the existing network storage and Library:
/// its Subsonic connection and its Library source. Faked in tests.
abstract interface class LinkLibraryBridge {
Future<NetworkConnection?> connection(String connectionId);
Future<void> saveConnection(NetworkConnection connection);
/// Points the connection at the desktop's new `https://host:port`.
Future<void> updateAddress(String connectionId, String address);
/// Adds the connection's root to Library and scans it, as the network
/// storage screen does after adding a Subsonic server.
Future<void> addLibrarySource(NetworkConnection connection);
/// Rescans the connection's Library source incrementally, after any
/// running scan.
Future<void> rescan(String connectionId);
/// Removes the Library source and the saved connection.
Future<void> removeConnection(String connectionId);
}
class LinkNetworkLibraryBridge implements LinkLibraryBridge {
LinkNetworkLibraryBridge(
this._ref, {
NetworkStorageService? storage,
LibraryDatabase? database,
}) : _storage = storage ?? NetworkStorageService.instance,
_database = database ?? LibraryDatabase.instance;
final Ref _ref;
final NetworkStorageService _storage;
final LibraryDatabase _database;
final _pendingScans = <String>{};
ProviderSubscription<bool>? _scanWatch;
static String _rootSource(String connectionId) =>
NetworkStorageService.source(connectionId, '');
@override
Future<NetworkConnection?> connection(String connectionId) async {
try {
return await _storage.connection(connectionId);
} on StateError {
return null;
}
}
@override
Future<void> saveConnection(NetworkConnection connection) =>
_storage.save(connection);
@override
Future<void> updateAddress(String connectionId, String address) async {
final current = await connection(connectionId);
if (current == null || current.address == address) return;
await _storage.save(
NetworkConnection(
id: current.id,
name: current.name,
protocol: current.protocol,
address: address,
username: current.username,
password: current.password,
domain: current.domain,
trustedCertificateSha256: current.trustedCertificateSha256,
subsonicAuth: current.subsonicAuth,
apiKey: current.apiKey,
),
);
}
@override
Future<void> addLibrarySource(NetworkConnection connection) async {
final source = await _ref
.read(localLibraryProvider.notifier)
.addSource(
path: _rootSource(connection.id),
displayName: connection.name,
);
_ref.read(settingsProvider.notifier).setLocalLibraryEnabled(true);
_scan(source.id);
}
@override
Future<void> rescan(String connectionId) async {
final source = await _database.getSourceByPath(_rootSource(connectionId));
if (source == null || !source.enabled) return;
_scan(source.id);
}
void _scan(String sourceId) {
if (_ref.read(localLibraryProvider).isScanning) {
// A request during another scan would be dropped; run it afterwards.
_pendingScans.add(sourceId);
_scanWatch ??= _ref.listen<bool>(
localLibraryProvider.select((state) => state.isScanning),
(_, scanning) {
if (!scanning) _drainPending();
},
);
return;
}
unawaited(
_ref
.read(localLibraryProvider.notifier)
.startSourceScan(sourceId)
.catchError((Object error) => _log.w('Library scan failed: $error')),
);
}
void _drainPending() {
_scanWatch?.close();
_scanWatch = null;
final pending = _pendingScans.toList();
_pendingScans.clear();
unawaited(() async {
final library = _ref.read(localLibraryProvider.notifier);
for (final sourceId in pending) {
try {
await library.startSourceScan(sourceId);
} catch (error) {
_log.w('Library scan failed: $error');
}
}
}());
}
@override
Future<void> removeConnection(String connectionId) async {
final source = await _database.getSourceByPath(_rootSource(connectionId));
if (source != null) {
_pendingScans.remove(source.id);
await _ref.read(localLibraryProvider.notifier).removeSource(source.id);
}
await _storage.remove(connectionId);
}
}
@@ -0,0 +1,276 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:mornye/services/link/client/link_client_http.dart';
import 'package:mornye/services/link/link_protocol.dart';
import 'package:mornye/services/local_network_access.dart';
/// How this phone introduces itself to a desktop.
@immutable
class LinkDeviceIdentity {
const LinkDeviceIdentity({
required this.deviceId,
required this.name,
required this.platform,
required this.appVersion,
});
final String deviceId;
final String name;
/// `android` or `ios`.
final String platform;
final String appVersion;
}
/// A desktop ready for its PIN: its `info`, read over a connection whose
/// certificate matched the fingerprint it claims.
@immutable
class LinkPairingTarget {
const LinkPairingTarget({required this.address, required this.info});
/// `https://host:port`.
final String address;
final LinkServerInfo info;
/// The fingerprint seen in the handshake, equal to [LinkServerInfo.fingerprint].
String get fingerprint => info.fingerprint;
/// The first 8 hex characters, which the desktop shows next to its PIN.
String get shortFingerprint => fingerprint.substring(0, 8);
}
@immutable
class LinkPairingResult {
const LinkPairingResult({
required this.apiKey,
required this.serverId,
required this.name,
required this.fingerprint,
});
final String apiKey;
final String serverId;
final String name;
final String fingerprint;
}
enum LinkPairingError {
/// The certificate in the handshake differs from the fingerprint the
/// desktop (or its mDNS record) claims: possibly someone in between.
certificateMismatch,
/// Not a Mornye desktop, or another protocol version.
incompatible,
invalidAddress,
/// The desktop answered `bad_proof`: the PIN is wrong.
badPin,
/// The desktop answered `pairing_closed`: no pairing window is open.
pairingClosed,
/// The desktop answered 429.
tooManyAttempts,
localNetworkPermission,
unreachable,
timeout,
failed,
}
class LinkPairingException implements Exception {
const LinkPairingException(this.error);
final LinkPairingError error;
@override
String toString() => 'LinkPairingException(${error.name})';
}
/// Pairing as the settings page drives it; faked in widget tests.
abstract interface class LinkPairingApi {
/// Reads `GET /mornye/v1/info` at [address] and checks the certificate.
/// [expectedFingerprint] is the one mDNS advertised, when known.
Future<LinkPairingTarget> probe(Uri address, {String? expectedFingerprint});
/// Sends the PIN proof; returns the device's API key.
Future<LinkPairingResult> pair(
LinkPairingTarget target, {
required String pin,
required LinkDeviceIdentity device,
});
}
final _pinPattern = RegExp(r'^\d{6}$');
/// Contract section 3 over HTTPS: first contact records the certificate,
/// then every request is pinned to it.
class LinkPairingClient implements LinkPairingApi {
LinkPairingClient({
Future<void> Function(Uri)? ensureAccess,
HttpClient Function(Uri target)? firstContactClient,
HttpClient Function(String fingerprint)? pinnedClient,
Duration timeout = linkRequestTimeout,
}) : _ensureAccess = ensureAccess ?? LocalNetworkAccess.instance.ensureAccess,
_firstContactClient = firstContactClient ?? linkFirstContactHttpClient,
_pinnedClient = pinnedClient ?? linkPinnedHttpClient,
_timeout = timeout;
final Future<void> Function(Uri) _ensureAccess;
final HttpClient Function(Uri target) _firstContactClient;
final HttpClient Function(String fingerprint) _pinnedClient;
final Duration _timeout;
@override
Future<LinkPairingTarget> probe(
Uri address, {
String? expectedFingerprint,
}) async {
if (address.scheme != 'https' || address.host.isEmpty) {
throw const LinkPairingException(LinkPairingError.invalidAddress);
}
final origin = Uri(scheme: 'https', host: address.host, port: address.port);
final client = _firstContactClient(origin);
try {
await _ensureAccess(origin);
final response = await linkHttpSend(
client,
'GET',
origin.replace(path: '$linkApiPath/info'),
timeout: _timeout,
);
if (!response.ok) {
throw const LinkPairingException(LinkPairingError.incompatible);
}
final info =
LinkServerInfo.fromJson(response.body) ??
(throw const LinkPairingException(LinkPairingError.incompatible));
final observed = response.certificateFingerprint;
if (!linkFingerprintsMatch(
observed: observed,
claimed: info.fingerprint,
advertised: expectedFingerprint,
)) {
throw const LinkPairingException(LinkPairingError.certificateMismatch);
}
if (info.protocol != linkProtocolVersion) {
throw const LinkPairingException(LinkPairingError.incompatible);
}
return LinkPairingTarget(address: origin.toString(), info: info);
} catch (error) {
throw _classify(error);
} finally {
client.close(force: true);
}
}
@override
Future<LinkPairingResult> pair(
LinkPairingTarget target, {
required String pin,
required LinkDeviceIdentity device,
}) async {
if (!_pinPattern.hasMatch(pin)) {
throw const LinkPairingException(LinkPairingError.badPin);
}
final origin = Uri.parse(target.address);
final client = _pinnedClient(target.fingerprint);
try {
await _ensureAccess(origin);
final response = await linkHttpSend(
client,
'POST',
origin.replace(path: '$linkApiPath/pair'),
json: {
'deviceId': device.deviceId,
'name': device.name,
'platform': device.platform,
'proof': linkPairingProof(
pin: pin,
fingerprint: target.fingerprint,
deviceId: device.deviceId,
),
},
timeout: _timeout,
);
final observed = response.certificateFingerprint;
if (observed != null && observed != target.fingerprint) {
throw const LinkPairingException(LinkPairingError.certificateMismatch);
}
final body = response.body;
if (response.statusCode == 429) {
throw const LinkPairingException(LinkPairingError.tooManyAttempts);
}
if (response.statusCode == 403) {
throw LinkPairingException(switch (body is Map ? body['error'] : null) {
'bad_proof' => LinkPairingError.badPin,
'pairing_closed' => LinkPairingError.pairingClosed,
_ => LinkPairingError.failed,
});
}
if (!response.ok || body is! Map) {
throw const LinkPairingException(LinkPairingError.failed);
}
final apiKey = body['apiKey'];
final serverId = body['serverId'];
final fingerprint = body['fingerprint'];
if (apiKey is! String || apiKey.isEmpty) {
throw const LinkPairingException(LinkPairingError.failed);
}
if (serverId is String && serverId != target.info.serverId) {
throw const LinkPairingException(LinkPairingError.incompatible);
}
if (fingerprint is String &&
fingerprint.toLowerCase() != target.fingerprint) {
throw const LinkPairingException(LinkPairingError.certificateMismatch);
}
final name = body['name'];
return LinkPairingResult(
apiKey: apiKey,
serverId: target.info.serverId,
name: name is String && name.trim().isNotEmpty
? name.trim()
: target.info.name,
fingerprint: target.fingerprint,
);
} catch (error) {
throw _classify(error);
} finally {
client.close(force: true);
}
}
static LinkPairingException _classify(Object error) => switch (error) {
LinkPairingException() => error,
LocalNetworkPermissionException() => const LinkPairingException(
LinkPairingError.localNetworkPermission,
),
// The pinned client refuses any other certificate during the handshake.
TlsException() => const LinkPairingException(
LinkPairingError.certificateMismatch,
),
TimeoutException() => const LinkPairingException(LinkPairingError.timeout),
SocketException() => const LinkPairingException(
LinkPairingError.unreachable,
),
FormatException() => const LinkPairingException(
LinkPairingError.invalidAddress,
),
_ => const LinkPairingException(LinkPairingError.failed),
};
}
/// Whether the certificate seen in the handshake ([observed]) is the one the
/// desktop claims in `info` and, when known, the one its mDNS record
/// advertises. Without an observed certificate nothing can be trusted.
bool linkFingerprintsMatch({
required String? observed,
required String claimed,
String? advertised,
}) {
if (observed == null || observed.isEmpty) return false;
final seen = observed.toLowerCase();
return seen == claimed.toLowerCase() &&
(advertised == null || advertised.toLowerCase() == seen);
}
@@ -0,0 +1,470 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:mornye/services/link/client/link_client_http.dart';
import 'package:mornye/services/link/client/link_client_pairing.dart';
import 'package:mornye/services/link/link_client_api.dart';
import 'package:mornye/services/link/link_protocol.dart';
import 'package:mornye/services/local_network_access.dart';
import 'package:mornye/utils/logger.dart';
final _log = AppLogger('LinkSession');
/// Why the session last failed to connect, for the settings page.
enum LinkSessionIssue {
unreachable,
/// The desktop refused the API key (revoked, or the record lost its key).
unauthorized,
/// The desktop presented a certificate other than the pinned one.
certificate,
localNetworkPermission,
/// The desktop speaks another protocol version.
incompatible,
}
/// A [LinkClientApi] the client controller can drive.
abstract interface class LinkSession implements LinkClientApi {
LinkSessionIssue? get issue;
/// Connects and keeps reconnecting until [dispose].
void start();
/// Closes the socket and stops retrying (app in the background).
void pause();
/// Reconnects at once after [pause].
void resume();
/// Skips the remaining backoff (discovery saw the desktop again).
void reconnectNow();
/// Uses [server]'s new address; reconnects when it changed.
void updateServer(LinkServerRecord server);
Future<void> dispose();
}
/// The WebSocket as the session uses it, so tests can fake it.
abstract interface class LinkSocket {
Stream<dynamic> get stream;
int? get closeCode;
void add(String data);
Future<void> close([int? code, String? reason]);
}
typedef LinkSocketConnector =
Future<LinkSocket> Function(
Uri uri,
Map<String, dynamic> headers,
HttpClient client,
);
typedef LinkTimerFactory = Timer Function(Duration delay, void Function() run);
class _WebSocketLinkSocket implements LinkSocket {
_WebSocketLinkSocket(this._socket) {
// The desktop pings every 20 s; pinging back finds a vanished desktop.
_socket.pingInterval = const Duration(seconds: 20);
}
final WebSocket _socket;
@override
Stream<dynamic> get stream => _socket;
@override
int? get closeCode => _socket.closeCode;
@override
void add(String data) => _socket.add(data);
@override
Future<void> close([int? code, String? reason]) =>
_socket.close(code, reason);
}
/// Opens the desktop's WebSocket over the session's (pinned) client.
Future<LinkSocket> linkConnectWebSocket(
Uri uri,
Map<String, dynamic> headers,
HttpClient client,
) async => _WebSocketLinkSocket(
await WebSocket.connect(
uri.toString(),
headers: headers,
customClient: client,
),
);
/// WebSocket close code for a key that belongs to another device.
const linkCloseUnauthorized = 4401;
final _opPattern = RegExp(r'^[A-Za-z0-9_.-]+(/[A-Za-z0-9_.-]+)*$');
/// Whether [op] names a path under the API: plain segments, none of them
/// `.` or `..`, which would resolve outside `/mornye/v1`.
bool _validOp(String op) =>
_opPattern.hasMatch(op) &&
op.split('/').every((segment) => segment != '.' && segment != '..');
/// The phone's live session with one paired desktop: Bearer JSON requests
/// and the WebSocket (`hello`, `welcome`, pushed messages), reconnecting
/// with backoff from [minBackoff] doubling to [maxBackoff].
class LinkClientSession implements LinkSession {
LinkClientSession({
required LinkServerRecord server,
required String apiKey,
required LinkDeviceIdentity device,
HttpClient Function(LinkServerRecord server)? httpClient,
LinkSocketConnector? connectSocket,
Future<void> Function(Uri)? ensureAccess,
LinkTimerFactory? timer,
Duration requestTimeout = linkRequestTimeout,
Duration handshakeTimeout = const Duration(seconds: 15),
}) : _server = server,
_apiKey = apiKey,
_device = device,
_createHttpClient =
httpClient ?? ((server) => linkPinnedHttpClient(server.fingerprint)),
_connectSocket = connectSocket ?? linkConnectWebSocket,
_ensureAccess = ensureAccess ?? LocalNetworkAccess.instance.ensureAccess,
_timer = timer ?? Timer.new,
_requestTimeout = requestTimeout,
_handshakeTimeout = handshakeTimeout;
static const minBackoff = Duration(seconds: 1);
static const maxBackoff = Duration(seconds: 30);
LinkServerRecord _server;
final String _apiKey;
final LinkDeviceIdentity _device;
final HttpClient Function(LinkServerRecord server) _createHttpClient;
final LinkSocketConnector _connectSocket;
final Future<void> Function(Uri) _ensureAccess;
final LinkTimerFactory _timer;
final Duration _requestTimeout;
final Duration _handshakeTimeout;
final _states = StreamController<LinkConnectionState>.broadcast();
final _messages = StreamController<Map<String, dynamic>>.broadcast();
HttpClient? _http;
LinkSocket? _socket;
StreamSubscription<dynamic>? _subscription;
Timer? _retry;
var _state = LinkConnectionState.disconnected;
LinkSessionIssue? _issue;
var _backoff = minBackoff;
var _attempt = 0;
var _started = false;
var _paused = false;
var _disposed = false;
@override
LinkServerRecord get server => _server;
@override
LinkConnectionState get connectionState => _state;
@override
Stream<LinkConnectionState> get connectionStates => _states.stream;
@override
Stream<Map<String, dynamic>> get messages => _messages.stream;
@override
LinkSessionIssue? get issue => _issue;
HttpClient get _client => _http ??= _createHttpClient(_server);
Uri get _origin => Uri.parse(_server.address);
Map<String, String> get _authorization => {
HttpHeaders.authorizationHeader: 'Bearer $_apiKey',
};
void _setState(LinkConnectionState next) {
if (_state == next || _disposed) return;
_state = next;
_states.add(next);
}
@override
void start() {
if (_disposed) return;
_started = true;
unawaited(_connect());
}
@override
void pause() {
if (_disposed || _paused) return;
_paused = true;
_dropSocket(1001);
}
@override
void resume() {
if (_disposed || !_paused) return;
_paused = false;
_backoff = minBackoff;
unawaited(_connect());
}
@override
void reconnectNow() {
if (_disposed || _paused || !_started) return;
if (_state != LinkConnectionState.disconnected) return;
_backoff = minBackoff;
unawaited(_connect());
}
@override
void updateServer(LinkServerRecord server) {
if (_disposed) return;
final moved =
server.address != _server.address ||
server.fingerprint != _server.fingerprint;
_server = server;
if (!moved) return;
_http?.close(force: true);
_http = null;
_dropSocket(1001);
_backoff = minBackoff;
if (_started && !_paused) unawaited(_connect());
}
/// Closes the socket and forgets pending connects and retries.
void _dropSocket(int code) {
_attempt++;
_retry?.cancel();
_retry = null;
unawaited(_subscription?.cancel());
_subscription = null;
final socket = _socket;
_socket = null;
unawaited(socket?.close(code).catchError((Object _) {}));
_setState(LinkConnectionState.disconnected);
}
Future<void> _connect() async {
if (_disposed || _paused || !_started) return;
if (_state != LinkConnectionState.disconnected) return;
_retry?.cancel();
_retry = null;
final attempt = ++_attempt;
_setState(LinkConnectionState.connecting);
LinkSocket? socket;
try {
final origin = _origin;
await _ensureAccess(origin);
if (attempt != _attempt) return;
final uri = origin.replace(
scheme: origin.scheme == 'http' ? 'ws' : 'wss',
path: linkSocketPath,
);
socket = await _connectSocket(
uri,
_authorization,
_client,
).timeout(_handshakeTimeout);
if (attempt != _attempt) {
unawaited(socket.close(1001).catchError((Object _) {}));
return;
}
final opened = socket;
final welcome = Completer<Map<String, dynamic>>();
var welcomed = false;
_socket = opened;
_subscription = opened.stream.listen(
(data) {
final message = _decode(data);
if (message == null) return;
if (!welcomed) {
welcomed = true;
if (!welcome.isCompleted) welcome.complete(message);
return;
}
if (attempt == _attempt) _messages.add(message);
},
onError: (Object error) {
if (!welcome.isCompleted) {
welcome.completeError(error);
} else {
_closed(attempt, opened);
}
},
onDone: () {
if (!welcome.isCompleted) {
welcome.completeError(
opened.closeCode == linkCloseUnauthorized
? const LinkException(LinkClientErrors.unauthorized)
: const SocketException('The computer closed the link'),
);
} else {
_closed(attempt, opened);
}
},
cancelOnError: true,
);
opened.add(
jsonEncode({
'type': LinkMessageTypes.hello,
'deviceId': _device.deviceId,
'name': _device.name,
'platform': _device.platform,
'appVersion': _device.appVersion,
'protocol': linkProtocolVersion,
}),
);
final reply = await welcome.future.timeout(_handshakeTimeout);
if (attempt != _attempt) return;
final serverId = reply['serverId'];
if (reply['type'] != LinkMessageTypes.welcome ||
reply['protocol'] != linkProtocolVersion ||
(serverId is String && serverId != _server.serverId)) {
throw const LinkException('incompatible');
}
_issue = null;
_backoff = minBackoff;
_setState(LinkConnectionState.connected);
} catch (error) {
if (attempt != _attempt || _disposed) {
if (socket != null && !identical(socket, _socket)) {
unawaited(socket.close(1001).catchError((Object _) {}));
}
return;
}
_issue = _issueFor(error);
_log.w('Connecting to the computer failed: ${_issue!.name}');
_dropSocket(1000);
_scheduleRetry();
}
}
void _closed(int attempt, LinkSocket socket) {
if (attempt != _attempt || _disposed) return;
if (socket.closeCode == linkCloseUnauthorized) {
_issue = LinkSessionIssue.unauthorized;
}
_dropSocket(1000);
_scheduleRetry();
}
void _scheduleRetry() {
if (_disposed || _paused || !_started) return;
// A refused key or certificate will not fix itself quickly, and a
// denied permission waits for the person; retry slowly or not at all.
if (_issue == LinkSessionIssue.localNetworkPermission) return;
if (_issue == LinkSessionIssue.unauthorized ||
_issue == LinkSessionIssue.certificate ||
_issue == LinkSessionIssue.incompatible) {
_backoff = maxBackoff;
}
final delay = _backoff;
_backoff = Duration(
milliseconds: min(_backoff.inMilliseconds * 2, maxBackoff.inMilliseconds),
);
_retry = _timer(delay, () {
_retry = null;
unawaited(_connect());
});
}
static LinkSessionIssue _issueFor(Object error) =>
switch (linkTransportException(error).code) {
LinkClientErrors.unauthorized => LinkSessionIssue.unauthorized,
LinkClientErrors.certificate => LinkSessionIssue.certificate,
LinkClientErrors.localNetworkPermission =>
LinkSessionIssue.localNetworkPermission,
'incompatible' => LinkSessionIssue.incompatible,
_ => LinkSessionIssue.unreachable,
};
static Map<String, dynamic>? _decode(Object? data) {
if (data is! String) return null;
try {
final decoded = jsonDecode(data);
if (decoded is Map<String, dynamic> && decoded['type'] is String) {
return decoded;
}
} on FormatException {
// Ignore frames that are not JSON objects.
}
return null;
}
@override
void send(Map<String, dynamic> message) {
final socket = _socket;
if (_state != LinkConnectionState.connected || socket == null) return;
try {
socket.add(jsonEncode(message));
} catch (error) {
_log.w('Sending to the computer failed: $error');
}
}
@override
Future<Object?> get(String op, [Map<String, String> query = const {}]) =>
_request('GET', op, query: query);
@override
Future<Object?> post(String op, Map<String, dynamic> body) =>
_request('POST', op, body: body);
Future<Object?> _request(
String method,
String op, {
Map<String, String> query = const {},
Map<String, dynamic>? body,
}) async {
if (_disposed) {
throw const LinkException(
LinkClientErrors.unavailable,
'The link was closed',
);
}
if (!_validOp(op)) {
throw LinkException(LinkClientErrors.invalid, 'Invalid operation $op');
}
final origin = _origin;
final uri = origin.replace(
path: '$linkApiPath/$op',
queryParameters: query.isEmpty ? null : query,
);
final LinkHttpResponse response;
try {
await _ensureAccess(origin);
response = await linkHttpSend(
_client,
method,
uri,
headers: _authorization,
json: method == 'GET' ? null : body,
timeout: _requestTimeout,
);
} catch (error) {
throw linkTransportException(error);
}
if (response.ok) return response.body;
final failure = linkResponseException(response);
if (response.statusCode == 401) _issue = LinkSessionIssue.unauthorized;
throw failure;
}
@override
Future<void> dispose() async {
if (_disposed) return;
_dropSocket(1000);
_disposed = true;
_http?.close(force: true);
_http = null;
await _states.close();
await _messages.close();
}
}
@@ -0,0 +1,125 @@
import 'dart:convert';
import 'dart:math';
import 'package:mornye/services/link/link_client_api.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// Paired desktops, the chosen one and this phone's device id, kept in
/// shared preferences. API keys stay in the network connection (secure
/// storage), never here.
class LinkClientStore {
LinkClientStore({
Future<SharedPreferences> Function()? preferences,
Random? random,
}) : _preferences = preferences ?? SharedPreferences.getInstance,
_random = random ?? Random.secure();
static const serversKey = 'link_client_servers';
static const deviceIdKey = 'link_client_device_id';
static const activeServerKey = 'link_client_active_server';
final Future<SharedPreferences> Function() _preferences;
final Random _random;
Future<void> _mutation = Future.value();
Future<T> _mutate<T>(Future<T> Function() action) {
final result = _mutation.then((_) => action());
_mutation = result.then<void>((_) {}, onError: (Object _) {});
return result;
}
/// This phone's id towards every desktop: random, created once.
Future<String> deviceId() => _mutate(() async {
final preferences = await _preferences();
final existing = preferences.getString(deviceIdKey);
if (existing != null && existing.length >= 16) return existing;
final id = _uuid();
await preferences.setString(deviceIdKey, id);
return id;
});
String _uuid() {
final bytes = List<int>.generate(16, (_) => _random.nextInt(256));
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-'
'${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}';
}
Future<List<LinkServerRecord>> servers() async => _read(await _preferences());
List<LinkServerRecord> _read(SharedPreferences preferences) {
final raw = preferences.getString(serversKey);
if (raw == null) return const [];
try {
final decoded = jsonDecode(raw);
if (decoded is! List) return const [];
final seen = <String>{};
return List.unmodifiable([
for (final row in decoded)
if (LinkServerRecord.fromJson(row) case final record?
when seen.add(record.serverId))
record,
]);
} on FormatException {
return const [];
}
}
Future<List<LinkServerRecord>> _write(
List<LinkServerRecord> Function(List<LinkServerRecord> current) change,
) => _mutate(() async {
final preferences = await _preferences();
final next = List<LinkServerRecord>.unmodifiable(
change([..._read(preferences)]),
);
await preferences.setString(
serversKey,
jsonEncode([for (final record in next) record.toJson()]),
);
return next;
});
/// Adds [record], or replaces the record with its server id in place.
Future<List<LinkServerRecord>> upsert(LinkServerRecord record) =>
_write((current) {
final index = current.indexWhere((r) => r.serverId == record.serverId);
if (index < 0) return current..add(record);
return current..[index] = record;
});
Future<List<LinkServerRecord>> remove(String serverId) =>
_write((current) => current..removeWhere((r) => r.serverId == serverId));
/// Moves a paired desktop to [address] (`https://host:port`).
Future<List<LinkServerRecord>> updateAddress(
String serverId,
String address,
) => _write(
(current) => [
for (final record in current)
record.serverId == serverId
? LinkServerRecord(
serverId: record.serverId,
name: record.name,
connectionId: record.connectionId,
address: address,
fingerprint: record.fingerprint,
)
: record,
],
);
Future<String?> activeServerId() async =>
(await _preferences()).getString(activeServerKey);
Future<void> setActiveServerId(String? serverId) => _mutate(() async {
final preferences = await _preferences();
if (serverId == null) {
await preferences.remove(activeServerKey);
} else {
await preferences.setString(activeServerKey, serverId);
}
});
}
@@ -9,6 +9,7 @@ import app_links
import audio_service
import audio_session
import audioplayers_darwin
import bonsoir_darwin
import connectivity_plus
import dart_smb2
import desktop_drop
@@ -30,6 +31,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
AudioServicePlugin.register(with: registry.registrar(forPlugin: "AudioServicePlugin"))
AudioSessionPlugin.register(with: registry.registrar(forPlugin: "AudioSessionPlugin"))
AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin"))
SwiftBonsoirPlugin.register(with: registry.registrar(forPlugin: "SwiftBonsoirPlugin"))
ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin"))
DartSmb2Plugin.register(with: registry.registrar(forPlugin: "DartSmb2Plugin"))
DesktopDropPlugin.register(with: registry.registrar(forPlugin: "DesktopDropPlugin"))
+48
View File
@@ -190,6 +190,54 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.4.1"
bonsoir:
dependency: "direct main"
description:
name: bonsoir
sha256: "20fed01e4616e625f4bafd9007ff899d231d8d79bebc8564853fa1e3570294a6"
url: "https://pub.dev"
source: hosted
version: "7.1.5"
bonsoir_android:
dependency: transitive
description:
name: bonsoir_android
sha256: "0dda1164e826553b8ee90a3fd1aabd462d17f19348f542b95f9d5b5455e4157f"
url: "https://pub.dev"
source: hosted
version: "7.1.3"
bonsoir_darwin:
dependency: transitive
description:
name: bonsoir_darwin
sha256: "6f695a0b4465514b75fc1a457746ab6dfc10d7180f0d04810fd9512e6520df69"
url: "https://pub.dev"
source: hosted
version: "7.1.1"
bonsoir_linux:
dependency: transitive
description:
name: bonsoir_linux
sha256: "9afae7bb9509c5bd20a0ea2ca02a0f2b1ef09cca1ceb2ea288ed58a0f03d1e11"
url: "https://pub.dev"
source: hosted
version: "7.1.0"
bonsoir_platform_interface:
dependency: transitive
description:
name: bonsoir_platform_interface
sha256: "6c55c786b01ad279f675ae72cea3a885aa746e416d2e8c1f0c46e9d2c06420b0"
url: "https://pub.dev"
source: hosted
version: "7.0.0"
bonsoir_windows:
dependency: transitive
description:
name: bonsoir_windows
sha256: aaabbb652fe68d3eb26a9b2cddefaae26cd9ca6ebe737d476ab9ed535c7c2516
url: "https://pub.dev"
source: hosted
version: "7.3.0"
boolean_selector:
dependency: transitive
description:
+2
View File
@@ -44,6 +44,8 @@ dependencies:
# 7.3.2 requires dbus 0.8, while desktop_drop 0.8.4 still requires 0.7.
connectivity_plus: ^7.3.1
crypto: ^3.0.7
# Mornye Link: finds the desktop app on the local network (mDNS).
bonsoir: ^7.1.5
# Streaming backup archives
archive: ^4.5.2
+364
View File
@@ -0,0 +1,364 @@
import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mornye/services/link/client/link_client_controller.dart';
import 'package:mornye/services/link/client/link_client_discovery.dart';
import 'package:mornye/services/link/client/link_client_pairing.dart';
import 'package:mornye/services/link/client/link_client_session.dart';
import 'package:mornye/services/link/client/link_client_store.dart';
import 'package:mornye/services/link/link_client_api.dart';
import 'package:mornye/services/link/link_protocol.dart';
import 'package:mornye/services/local_network_access.dart';
import 'package:mornye/services/network_storage_service.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'support/link_client_fakes.dart';
Future<LinkClientHarness> _started({
bool supported = true,
bool localNetworkAllowed = true,
bool onWifi = true,
}) async {
final harness = LinkClientHarness(supported: supported)
..localNetworkAllowed = localNetworkAllowed
..onWifi = onWifi;
addTearDown(harness.container.dispose);
await harness.start();
await pumpEventQueue();
return harness;
}
Future<void> _lifecycle(List<AppLifecycleState> states) async {
for (final state in states) {
TestWidgetsFlutterBinding.instance.handleAppLifecycleStateChanged(state);
}
await pumpEventQueue();
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
SharedPreferences.setMockInitialValues({});
TestWidgetsFlutterBinding.instance.handleAppLifecycleStateChanged(
AppLifecycleState.resumed,
);
});
test('pairing publishes the first desktop and follows the choice', () async {
final harness = await _started();
expect(harness.state.loaded, isTrue);
expect(harness.state.activeServerId, isNull);
expect(harness.active, isNull);
final a = await harness.controller.pair(linkTestTarget('a'), '123456');
await pumpEventQueue();
expect(harness.pairing.pins, ['123456']);
final device = harness.pairing.devices.single;
expect(device.name, 'Test phone');
expect(device.platform, 'android');
expect(device.deviceId, await LinkClientStore().deviceId());
final connection = harness.bridge.connections[a.connectionId]!;
expect(connection.protocol, NetworkProtocol.subsonic);
expect(connection.subsonicAuth, SubsonicAuth.apiKey);
expect(connection.apiKey, 'key-1');
expect(connection.address, 'https://10.0.0.2:47710');
expect(connection.name, 'Desktop a');
expect(connection.trustedCertificateSha256, linkTestFingerprint('a'));
expect(harness.bridge.calls, [
'save ${a.connectionId}',
'source ${a.connectionId}',
]);
expect(harness.state.activeServerId, 'a');
expect(harness.sessions, hasLength(1));
final first = harness.sessions.single;
expect(harness.active, same(first));
expect(first.apiKey, 'key-1');
expect(first.calls, ['start']);
final stored = await LinkClientStore().servers();
expect(stored.single.toJson(), a.toJson());
// A second desktop does not take over.
await harness.controller.pair(
linkTestTarget('b', host: '10.0.0.3'),
'654321',
);
await pumpEventQueue();
expect(harness.state.servers.map((s) => s.serverId), ['a', 'b']);
expect(harness.sessions, hasLength(1));
expect(harness.active, same(first));
await harness.controller.setActive('b');
await pumpEventQueue();
expect(harness.sessions, hasLength(2));
expect(first.disposed, isTrue);
expect(harness.active, same(harness.sessions.last));
expect(harness.active!.server.serverId, 'b');
expect(await LinkClientStore().activeServerId(), 'b');
final b = harness.state.activeServer!;
await harness.controller.forget('b', removeLibrary: true);
await pumpEventQueue();
expect(harness.state.activeServerId, 'a');
expect(harness.active!.server.serverId, 'a');
expect(harness.sessions[1].disposed, isTrue);
expect(harness.bridge.calls.last, 'remove ${b.connectionId}');
await harness.controller.forget('a', removeLibrary: false);
await pumpEventQueue();
expect(harness.state.servers, isEmpty);
expect(harness.active, isNull);
expect(harness.bridge.connections, contains(a.connectionId));
expect(await LinkClientStore().servers(), isEmpty);
});
test('re-pairing replaces the key and keeps the connection', () async {
final harness = await _started();
final first = await harness.controller.pair(linkTestTarget('a'), '111111');
harness.pairing.key = 'key-2';
final second = await harness.controller.pair(
linkTestTarget('a', host: '10.0.0.9'),
'222222',
);
await pumpEventQueue();
expect(second.connectionId, first.connectionId);
expect(harness.state.servers, hasLength(1));
expect(harness.state.servers.single.address, 'https://10.0.0.9:47710');
expect(harness.bridge.connections[first.connectionId]!.apiKey, 'key-2');
expect(harness.sessions.last.apiKey, 'key-2');
expect(harness.sessions.first.disposed, isTrue);
expect(harness.active, same(harness.sessions.last));
});
test('a failed pairing saves nothing', () async {
final harness = await _started();
harness.pairing.error = LinkPairingError.badPin;
await expectLater(
harness.controller.pair(linkTestTarget('a'), '000000'),
throwsA(
isA<LinkPairingException>().having(
(e) => e.error,
'error',
LinkPairingError.badPin,
),
),
);
expect(harness.state.servers, isEmpty);
expect(harness.bridge.calls, isEmpty);
expect(harness.active, isNull);
});
test('a bad address fails before any request', () async {
final harness = await _started();
await expectLater(
harness.controller.probe('host/path', 47710),
throwsA(
isA<LinkPairingException>().having(
(e) => e.error,
'error',
LinkPairingError.invalidAddress,
),
),
);
expect(harness.pairing.probes, isEmpty);
});
test('stored desktops load with the saved active choice', () async {
final records = [
for (final id in ['a', 'b'])
LinkServerRecord(
serverId: id,
name: 'Desktop $id',
connectionId: 'connection-$id',
address: 'https://10.0.0.2:47710',
fingerprint: linkTestFingerprint(id),
),
];
SharedPreferences.setMockInitialValues({
LinkClientStore.serversKey: jsonEncode([
for (final record in records) record.toJson(),
]),
LinkClientStore.activeServerKey: 'b',
});
final harness = LinkClientHarness();
addTearDown(harness.container.dispose);
harness.bridge.connections['connection-b'] = const NetworkConnection(
id: 'connection-b',
name: 'Desktop b',
protocol: NetworkProtocol.subsonic,
address: 'https://10.0.0.2:47710',
subsonicAuth: SubsonicAuth.apiKey,
apiKey: 'stored-key',
);
await harness.start();
await pumpEventQueue();
expect(harness.state.servers, hasLength(2));
expect(harness.state.activeServerId, 'b');
expect(harness.sessions.single.apiKey, 'stored-key');
expect(harness.active, same(harness.sessions.single));
// A desktop whose connection was removed elsewhere must pair again.
await harness.controller.setActive('a');
await pumpEventQueue();
expect(harness.active, isNull);
expect(harness.state.issue, LinkSessionIssue.unauthorized);
});
test('state follows the session and discovery follows the desktop', () async {
final harness = await _started();
final record = await harness.controller.pair(linkTestTarget('a'), '123456');
await pumpEventQueue();
final session = harness.sessions.single;
// Disconnected: discovery looks for the desktop.
expect(harness.browser.started, 1);
expect(harness.state.discovery, LinkDiscoveryStatus.searching);
session.emit(LinkConnectionState.connected);
await pumpEventQueue();
expect(harness.state.connection, LinkConnectionState.connected);
expect(harness.browser.stopped, 1);
session.emit(
LinkConnectionState.disconnected,
LinkSessionIssue.unreachable,
);
await pumpEventQueue();
expect(harness.state.issue, LinkSessionIssue.unreachable);
expect(harness.browser.started, 2);
// Seen again at the same address: reconnect at once.
harness.browser.resolve('a', '10.0.0.2');
await pumpEventQueue();
expect(session.calls.last, 'reconnect');
// Seen at a new address: the record, connection and session move.
harness.browser.resolve('a', '10.0.0.7');
await pumpEventQueue();
expect(harness.state.servers.single.address, 'https://10.0.0.7:47710');
expect(
(await LinkClientStore().servers()).single.address,
'https://10.0.0.7:47710',
);
expect(
harness.bridge.calls.last,
'address ${record.connectionId} https://10.0.0.7:47710',
);
expect(session.calls.last, 'update https://10.0.0.7:47710');
});
test('another certificate under a known id is not followed', () async {
final harness = await _started();
await harness.controller.pair(linkTestTarget('a'), '123456');
await pumpEventQueue();
final session = harness.sessions.single;
harness.browser.resolve('a', '10.0.0.66', fingerprint: 'cc' * 32);
await pumpEventQueue();
expect(harness.state.servers.single.address, 'https://10.0.0.2:47710');
expect(session.calls, ['start']);
expect(
harness.state.certificateChanged(harness.state.activeServer!),
isTrue,
);
});
test('the session pauses in the background and resumes after', () async {
final harness = await _started();
await harness.controller.pair(linkTestTarget('a'), '123456');
await pumpEventQueue();
final session = harness.sessions.single;
await _lifecycle([AppLifecycleState.inactive]);
expect(session.calls, ['start']);
await _lifecycle([AppLifecycleState.hidden, AppLifecycleState.paused]);
expect(session.calls, ['start', 'pause']);
expect(harness.browser.stopped, 1);
await _lifecycle([
AppLifecycleState.hidden,
AppLifecycleState.inactive,
AppLifecycleState.resumed,
]);
expect(session.calls, ['start', 'pause', 'resume']);
expect(harness.browser.started, 2);
});
test('catalog.changed rescans the desktop once bursts settle', () async {
final harness = await _started();
final record = await harness.controller.pair(linkTestTarget('a'), '123456');
await pumpEventQueue();
final session = harness.sessions.single;
session.push({'type': LinkMessageTypes.catalogChanged, 'version': 1});
session.push({'type': 'player.state'});
session.push({'type': LinkMessageTypes.catalogChanged, 'version': 2});
await pumpEventQueue();
expect(harness.bridge.calls.where((c) => c.startsWith('rescan')), isEmpty);
await Future<void>.delayed(
LinkClientController.rescanDelay + const Duration(milliseconds: 200),
);
expect(harness.bridge.calls.where((c) => c.startsWith('rescan')), [
'rescan ${record.connectionId}',
]);
});
test('a refused permission stops discovery until asked again', () async {
final harness = await _started(localNetworkAllowed: false);
final release = harness.controller.acquireDiscovery();
addTearDown(release);
await pumpEventQueue();
expect(harness.state.discovery, LinkDiscoveryStatus.permissionDenied);
expect(harness.browser.started, 0);
await expectLater(
harness.controller.requestLocalNetworkAccess(),
throwsA(isA<LocalNetworkPermissionException>()),
);
harness.localNetworkAllowed = true;
await harness.controller.requestLocalNetworkAccess();
await pumpEventQueue();
expect(harness.state.discovery, LinkDiscoveryStatus.searching);
expect(harness.browser.started, 1);
harness.browser.resolve('b', '10.0.0.3');
await pumpEventQueue();
expect(harness.state.unpaired.single.serverId, 'b');
release();
await pumpEventQueue();
expect(harness.state.discovery, LinkDiscoveryStatus.idle);
expect(harness.state.discovered, isEmpty);
});
test('the page hears when Wi-Fi is off', () async {
final harness = await _started(onWifi: false);
harness.controller.acquireDiscovery()();
await pumpEventQueue();
expect(harness.state.localNetworkAvailable, isFalse);
});
test('disposing closes the session and discovery', () async {
final harness = LinkClientHarness();
await harness.start();
await harness.controller.pair(linkTestTarget('a'), '123456');
await pumpEventQueue();
harness.container.dispose();
await pumpEventQueue();
expect(harness.sessions.single.disposed, isTrue);
expect(harness.browser.stopped, 1);
});
test('unsupported platforms stay inert', () async {
final harness = await _started(supported: false);
expect(harness.state.loaded, isTrue);
harness.controller.acquireDiscovery();
await harness.controller.requestLocalNetworkAccess();
await pumpEventQueue();
expect(harness.browser.started, 0);
expect(harness.active, isNull);
final preferences = await SharedPreferences.getInstance();
expect(preferences.getKeys(), isEmpty);
});
}
+188
View File
@@ -0,0 +1,188 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:mornye/services/link/client/link_client_discovery.dart';
import 'package:mornye/services/local_network_access.dart';
final _fp = 'ab' * 32;
LinkServiceResolved _service({
String name = 'Studio PC',
int port = 47710,
List<String> addresses = const ['192.168.1.20'],
String? hostname,
Map<String, String>? attributes,
}) => LinkServiceResolved(
name: name,
port: port,
addresses: addresses,
hostname: hostname,
attributes: attributes ?? {'v': '1', 'id': 'server-1', 'fp': _fp},
);
class _FakeBrowser implements LinkServiceBrowser {
_FakeBrowser() {
// Stays open across stop() so late events can be checked. Not awaited:
// a stream nobody listened to never reports done.
addTearDown(() => unawaited(events.close()));
}
final events = StreamController<LinkServiceEvent>();
int started = 0;
int stopped = 0;
@override
Future<Stream<LinkServiceEvent>> start() async {
started++;
return events.stream;
}
@override
Future<void> stop() async => stopped++;
}
void main() {
group('service mapping', () {
test('reads id, fingerprint, host and port from the record', () {
final server = linkDiscoveredServerFrom(
_service(
attributes: {'v': '1', 'id': ' server-1 ', 'fp': _fp.toUpperCase()},
),
)!;
expect(server.serverId, 'server-1');
expect(server.fingerprint, _fp);
expect(server.name, 'Studio PC');
expect(server.address, 'https://192.168.1.20:47710');
});
test('ignores services of another version or without identity', () {
for (final attributes in [
{'v': '2', 'id': 'server-1', 'fp': _fp},
{'id': 'server-1', 'fp': _fp},
{'v': '1', 'fp': _fp},
{'v': '1', 'id': 'server-1', 'fp': 'not-hex'},
{'v': '1', 'id': 'server-1'},
]) {
expect(
linkDiscoveredServerFrom(_service(attributes: attributes)),
isNull,
reason: '$attributes',
);
}
expect(linkDiscoveredServerFrom(_service(port: 0)), isNull);
expect(linkDiscoveredServerFrom(_service(addresses: const [])), isNull);
});
test('prefers IPv4, then routable IPv6, then the host name', () {
expect(
linkPreferredHost(['fe80::1%wlan0', '2001:db8::5', '10.0.0.4'], null),
'10.0.0.4',
);
expect(
linkPreferredHost(['fe80::1', '2001:db8::5'], null),
'2001:db8::5',
);
expect(linkPreferredHost(['fe80::1'], 'studio.local.'), 'studio.local');
expect(linkPreferredHost(['127.0.0.1'], null), isNull);
expect(
linkDiscoveredServerFrom(
_service(addresses: const ['2001:db8::5']),
)!.address,
'https://[2001:db8::5]:47710',
);
});
});
group('LinkDiscovery', () {
test('tracks resolved and lost desktops', () async {
final browser = _FakeBrowser();
var changes = 0;
final discovery = LinkDiscovery(
createBrowser: () => browser,
ensureAccess: () async {},
onChanged: () => changes++,
);
await discovery.start();
expect(discovery.status, LinkDiscoveryStatus.searching);
expect(browser.started, 1);
browser.events.add(_service());
browser.events.add(
_service(
name: 'Laptop',
addresses: const ['192.168.1.30'],
attributes: {'v': '1', 'id': 'server-2', 'fp': 'cd' * 32},
),
);
await pumpEventQueue();
expect(discovery.servers.map((s) => s.name), ['Laptop', 'Studio PC']);
// An update without addresses keeps the resolved entry.
final before = changes;
browser.events.add(_service(addresses: const []));
await pumpEventQueue();
expect(changes, before);
expect(discovery.servers, hasLength(2));
// A move to another address replaces the entry.
browser.events.add(_service(addresses: const ['192.168.1.21']));
await pumpEventQueue();
expect(
discovery.servers.firstWhere((s) => s.serverId == 'server-1').host,
'192.168.1.21',
);
browser.events.add(const LinkServiceLost('Laptop'));
await pumpEventQueue();
expect(discovery.servers.map((s) => s.serverId), ['server-1']);
await discovery.stop();
expect(discovery.status, LinkDiscoveryStatus.idle);
expect(discovery.servers, isEmpty);
expect(browser.stopped, 1);
});
test('events after stop are ignored', () async {
final browser = _FakeBrowser();
final discovery = LinkDiscovery(
createBrowser: () => browser,
ensureAccess: () async {},
onChanged: () {},
);
await discovery.start();
await discovery.stop();
browser.events.add(_service());
await pumpEventQueue();
expect(discovery.servers, isEmpty);
});
test('a refused permission is reported, not retried', () async {
final browser = _FakeBrowser();
final discovery = LinkDiscovery(
createBrowser: () => browser,
ensureAccess: () async => throw const LocalNetworkPermissionException(),
onChanged: () {},
);
await discovery.start();
expect(discovery.status, LinkDiscoveryStatus.permissionDenied);
expect(discovery.running, isFalse);
expect(browser.started, 0);
});
test('a browser error stops discovery', () async {
final browser = _FakeBrowser();
final discovery = LinkDiscovery(
createBrowser: () => browser,
ensureAccess: () async {},
onChanged: () {},
);
await discovery.start();
browser.events.add(_service());
browser.events.addError(StateError('nsd failed'));
await pumpEventQueue();
expect(discovery.status, LinkDiscoveryStatus.failed);
expect(discovery.servers, isEmpty);
expect(browser.stopped, 1);
});
});
}
+354
View File
@@ -0,0 +1,354 @@
import 'dart:convert';
import 'dart:io';
import 'package:crypto/crypto.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mornye/services/link/client/link_client_http.dart';
import 'package:mornye/services/link/client/link_client_pairing.dart';
import 'package:mornye/services/link/link_protocol.dart';
const _device = LinkDeviceIdentity(
deviceId: 'phone-1',
name: 'Test phone',
platform: 'android',
appVersion: '1.0.0',
);
/// SHA-256 of the fixture certificate's DER bytes.
String _fixtureFingerprint() {
final pem = File('test/fixtures/network_tls/cert.pem').readAsStringSync();
final base64Body = pem
.split('\n')
.where((line) => line.isNotEmpty && !line.startsWith('-----'))
.join();
return sha256.convert(base64.decode(base64Body)).toString();
}
/// A desktop over TLS with the fixture certificate. [claimedFingerprint]
/// is what `info` reports; [onPair] answers `POST pair`.
Future<HttpServer> _desktop({
required String claimedFingerprint,
bool pairing = true,
int protocol = linkProtocolVersion,
Future<void> Function(HttpRequest request, Map<String, dynamic> body)? onPair,
}) async {
final context = SecurityContext()
..useCertificateChain('test/fixtures/network_tls/cert.pem')
..usePrivateKey('test/fixtures/network_tls/key.pem');
final server = await HttpServer.bindSecure(
InternetAddress.loopbackIPv4,
0,
context,
);
server.listen((request) async {
final response = request.response;
response.headers.contentType = ContentType.json;
if (request.uri.path == '/mornye/v1/info') {
response.write(
jsonEncode({
'serverId': 'server-1',
'name': 'Studio PC',
'protocol': protocol,
'appVersion': '5.3.0',
'fingerprint': claimedFingerprint,
'pairing': pairing,
}),
);
} else if (request.uri.path == '/mornye/v1/pair' &&
request.method == 'POST') {
final body =
jsonDecode(await utf8.decoder.bind(request).join())
as Map<String, dynamic>;
await onPair?.call(request, body);
} else {
response.statusCode = 404;
}
await response.close();
}, onError: (Object _) {});
return server;
}
void main() {
// TLS needs real sockets.
HttpOverrides.global = null;
final fingerprint = _fixtureFingerprint();
group('pinned client', () {
late HttpServer server;
setUp(() async {
server = await _desktop(claimedFingerprint: fingerprint);
});
tearDown(() => server.close(force: true));
Uri info() => Uri.parse('https://127.0.0.1:${server.port}/mornye/v1/info');
test('accepts exactly the pinned certificate', () async {
final client = linkPinnedHttpClient(fingerprint.toUpperCase());
addTearDown(() => client.close(force: true));
final response = await linkHttpSend(client, 'GET', info());
expect(response.statusCode, 200);
expect(response.certificateFingerprint, fingerprint);
});
test('refuses any other certificate during the handshake', () async {
final client = linkPinnedHttpClient('0' * 64);
addTearDown(() => client.close(force: true));
await expectLater(
linkHttpSend(client, 'GET', info()),
throwsA(isA<HandshakeException>()),
);
});
test('first contact accepts only the target and records it', () async {
final target = Uri.parse('https://127.0.0.1:${server.port}');
final client = linkFirstContactHttpClient(target);
addTearDown(() => client.close(force: true));
final response = await linkHttpSend(client, 'GET', info());
expect(response.certificateFingerprint, fingerprint);
final other = linkFirstContactHttpClient(
Uri.parse('https://127.0.0.1:${server.port + 1}'),
);
addTearDown(() => other.close(force: true));
await expectLater(
linkHttpSend(other, 'GET', info()),
throwsA(isA<HandshakeException>()),
);
});
});
group('pairing', () {
test('pairs with a proof over the observed fingerprint', () async {
Map<String, dynamic>? sent;
final server = await _desktop(
claimedFingerprint: fingerprint,
onPair: (request, body) async {
sent = body;
request.response.write(
jsonEncode({
'apiKey': 'key-1',
'serverId': 'server-1',
'name': 'Studio PC',
'fingerprint': fingerprint,
}),
);
},
);
addTearDown(() => server.close(force: true));
final client = LinkPairingClient();
final target = await client.probe(
Uri.parse('https://127.0.0.1:${server.port}'),
expectedFingerprint: fingerprint,
);
expect(target.address, 'https://127.0.0.1:${server.port}');
expect(target.info.serverId, 'server-1');
expect(target.info.pairing, isTrue);
expect(target.shortFingerprint, fingerprint.substring(0, 8));
final result = await client.pair(target, pin: '123456', device: _device);
expect(result.apiKey, 'key-1');
expect(result.serverId, 'server-1');
expect(result.name, 'Studio PC');
expect(result.fingerprint, fingerprint);
expect(sent, {
'deviceId': 'phone-1',
'name': 'Test phone',
'platform': 'android',
'proof': linkPairingProof(
pin: '123456',
fingerprint: fingerprint,
deviceId: 'phone-1',
),
});
});
test('aborts when info claims another certificate', () async {
final server = await _desktop(claimedFingerprint: 'a' * 64);
addTearDown(() => server.close(force: true));
await expectLater(
LinkPairingClient().probe(
Uri.parse('https://127.0.0.1:${server.port}'),
),
throwsA(
isA<LinkPairingException>().having(
(e) => e.error,
'error',
LinkPairingError.certificateMismatch,
),
),
);
});
test('aborts when mDNS advertised another certificate', () async {
final server = await _desktop(claimedFingerprint: fingerprint);
addTearDown(() => server.close(force: true));
await expectLater(
LinkPairingClient().probe(
Uri.parse('https://127.0.0.1:${server.port}'),
expectedFingerprint: 'b' * 64,
),
throwsA(
isA<LinkPairingException>().having(
(e) => e.error,
'error',
LinkPairingError.certificateMismatch,
),
),
);
});
test('refuses another protocol version', () async {
final server = await _desktop(
claimedFingerprint: fingerprint,
protocol: 2,
);
addTearDown(() => server.close(force: true));
await expectLater(
LinkPairingClient().probe(
Uri.parse('https://127.0.0.1:${server.port}'),
),
throwsA(
isA<LinkPairingException>().having(
(e) => e.error,
'error',
LinkPairingError.incompatible,
),
),
);
});
for (final (status, body, expected) in [
(403, {'error': 'bad_proof'}, LinkPairingError.badPin),
(403, {'error': 'pairing_closed'}, LinkPairingError.pairingClosed),
(429, {'error': 'rate_limited'}, LinkPairingError.tooManyAttempts),
(500, {'error': 'internal'}, LinkPairingError.failed),
]) {
test('maps $status ${body['error']} to ${expected.name}', () async {
final server = await _desktop(
claimedFingerprint: fingerprint,
onPair: (request, _) async {
request.response.statusCode = status;
request.response.write(jsonEncode(body));
},
);
addTearDown(() => server.close(force: true));
final client = LinkPairingClient();
final target = await client.probe(
Uri.parse('https://127.0.0.1:${server.port}'),
);
await expectLater(
client.pair(target, pin: '000000', device: _device),
throwsA(
isA<LinkPairingException>().having(
(e) => e.error,
'error',
expected,
),
),
);
});
}
test('a certificate swapped after info stops the pairing', () async {
final server = await _desktop(claimedFingerprint: fingerprint);
addTearDown(() => server.close(force: true));
final target = LinkPairingTarget(
address: 'https://127.0.0.1:${server.port}',
info: LinkServerInfo(
serverId: 'server-1',
name: 'Studio PC',
protocol: linkProtocolVersion,
appVersion: '5.3.0',
fingerprint: 'c' * 64,
pairing: true,
),
);
await expectLater(
LinkPairingClient().pair(target, pin: '123456', device: _device),
throwsA(
isA<LinkPairingException>().having(
(e) => e.error,
'error',
LinkPairingError.certificateMismatch,
),
),
);
});
test('rejects a PIN that is not six digits without a request', () async {
final target = LinkPairingTarget(
address: 'https://127.0.0.1:1',
info: LinkServerInfo(
serverId: 'server-1',
name: 'Studio PC',
protocol: linkProtocolVersion,
appVersion: '5.3.0',
fingerprint: fingerprint,
pairing: true,
),
);
await expectLater(
LinkPairingClient().pair(target, pin: '12a456', device: _device),
throwsA(
isA<LinkPairingException>().having(
(e) => e.error,
'error',
LinkPairingError.badPin,
),
),
);
});
test('an unreachable computer is reported as such', () async {
final socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = socket.port;
await socket.close();
await expectLater(
LinkPairingClient().probe(Uri.parse('https://127.0.0.1:$port')),
throwsA(
isA<LinkPairingException>().having(
(e) => e.error,
'error',
LinkPairingError.unreachable,
),
),
);
});
});
group('fingerprint checks', () {
test('need an observed certificate equal to every claim', () {
expect(
linkFingerprintsMatch(observed: 'ab', claimed: 'AB', advertised: 'ab'),
isTrue,
);
expect(linkFingerprintsMatch(observed: null, claimed: 'ab'), isFalse);
expect(linkFingerprintsMatch(observed: 'ab', claimed: 'cd'), isFalse);
expect(
linkFingerprintsMatch(observed: 'ab', claimed: 'ab', advertised: 'cd'),
isFalse,
);
});
test('server addresses accept hosts and refuse URLs', () {
expect(
linkServerAddress('192.168.1.20', 47710).toString(),
'https://192.168.1.20:47710',
);
expect(
linkServerAddress('fe80::2', 47710).toString(),
'https://[fe80::2]:47710',
);
expect(
linkServerAddress('[2001:db8::1]', 1).toString(),
'https://[2001:db8::1]:1',
);
expect(linkServerAddress('', 47710), isNull);
expect(linkServerAddress('host/path', 47710), isNull);
expect(linkServerAddress('host:1', 47710), isNull);
expect(linkServerAddress('host', 0), isNull);
expect(linkServerAddress('host', 70000), isNull);
});
});
}
+564
View File
@@ -0,0 +1,564 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:mornye/services/link/client/link_client_pairing.dart';
import 'package:mornye/services/link/client/link_client_session.dart';
import 'package:mornye/services/link/link_client_api.dart';
import 'package:mornye/services/link/link_protocol.dart';
const _device = LinkDeviceIdentity(
deviceId: 'phone-1',
name: 'Test phone',
platform: 'ios',
appVersion: '5.3.0',
);
LinkServerRecord _record(String address) => LinkServerRecord(
serverId: 'server-1',
name: 'Studio PC',
connectionId: 'connection-1',
address: address,
fingerprint: 'f' * 64,
);
const _welcome = {
'type': 'welcome',
'serverId': 'server-1',
'name': 'Studio PC',
'protocol': 1,
};
class _FakeTimer implements Timer {
_FakeTimer(this._run);
final void Function() _run;
var _active = true;
@override
bool get isActive => _active;
@override
int get tick => 0;
@override
void cancel() => _active = false;
void fire() {
if (!_active) return;
_active = false;
_run();
}
}
/// Records requested delays; tests fire retries by hand.
class _Timers {
final delays = <Duration>[];
final timers = <_FakeTimer>[];
Timer call(Duration delay, void Function() run) {
delays.add(delay);
final timer = _FakeTimer(run);
timers.add(timer);
return timer;
}
_FakeTimer get last => timers.last;
}
class _FakeSocket implements LinkSocket {
_FakeSocket({this.welcome = _welcome, this.closeBeforeWelcome});
final Map<String, dynamic>? welcome;
final int? closeBeforeWelcome;
final incoming = StreamController<dynamic>();
final sent = <Map<String, dynamic>>[];
int? _closeCode;
bool closed = false;
@override
Stream<dynamic> get stream => incoming.stream;
@override
int? get closeCode => _closeCode;
@override
void add(String data) {
final message = jsonDecode(data) as Map<String, dynamic>;
sent.add(message);
if (message['type'] != 'hello') return;
scheduleMicrotask(() {
if (closeBeforeWelcome case final code?) {
serverClose(code);
} else if (welcome case final reply?) {
incoming.add(jsonEncode(reply));
}
});
}
void push(Map<String, dynamic> message) => incoming.add(jsonEncode(message));
void serverClose([int code = 1001]) {
_closeCode = code;
unawaited(incoming.close());
}
@override
Future<void> close([int? code, String? reason]) async {
closed = true;
_closeCode ??= code;
unawaited(incoming.close());
}
}
void main() {
group('requests', () {
late HttpServer server;
late LinkClientSession session;
final requests = <HttpRequest>[];
final bodies = <String>[];
setUp(() async {
requests.clear();
bodies.clear();
server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
server.listen((request) async {
requests.add(request);
bodies.add(await utf8.decoder.bind(request).join());
final response = request.response;
switch (request.uri.path) {
case '/mornye/v1/state':
response.headers.contentType = ContentType.json;
response.write(jsonEncode({'playing': true}));
case '/mornye/v1/handoff/play':
response.headers.contentType = ContentType.json;
response.write(jsonEncode({'resolved': 2, 'missing': <String>[]}));
case '/mornye/v1/open':
response.statusCode = 204;
case '/mornye/v1/secret':
response.statusCode = 401;
default:
response.statusCode = 404;
response.headers.contentType = ContentType.json;
response.write(
jsonEncode({'error': 'not_found', 'message': 'No handler'}),
);
}
await response.close();
});
session = LinkClientSession(
server: _record('http://127.0.0.1:${server.port}'),
apiKey: 'key-1',
device: _device,
httpClient: (_) => HttpClient(),
ensureAccess: (_) async {},
);
});
tearDown(() async {
await session.dispose();
await server.close(force: true);
});
test('GET sends the bearer key and query, and decodes JSON', () async {
final result = await session.get(LinkOps.state, {'since': '5'});
expect(result, {'playing': true});
final request = requests.single;
expect(request.method, 'GET');
expect(request.uri.path, '/mornye/v1/state');
expect(request.uri.queryParameters, {'since': '5'});
expect(request.headers.value('authorization'), 'Bearer key-1');
expect(request.headers.value('accept'), 'application/json');
});
test('POST sends a JSON body to a nested op', () async {
final result = await session.post(LinkOps.handoffPlay, {
'index': 1,
'queue': <Object?>[],
});
expect(result, {'resolved': 2, 'missing': <Object?>[]});
expect(requests.single.method, 'POST');
expect(requests.single.headers.contentType?.mimeType, 'application/json');
expect(jsonDecode(bodies.single), {'index': 1, 'queue': <Object?>[]});
});
test('an empty success answers null', () async {
expect(await session.post(LinkOps.open, {'url': 'x'}), isNull);
});
test('error bodies become LinkException', () async {
await expectLater(
session.get('missing'),
throwsA(
isA<LinkException>()
.having((e) => e.code, 'code', 'not_found')
.having((e) => e.message, 'message', 'No handler'),
),
);
});
test('a bare 401 is unauthorized and marks the session', () async {
await expectLater(
session.get('secret'),
throwsA(
isA<LinkException>().having((e) => e.code, 'code', 'unauthorized'),
),
);
expect(session.issue, LinkSessionIssue.unauthorized);
});
test('operations outside the API path are refused locally', () async {
for (final op in [
'../rest/ping',
'library/../../rest',
'./state',
'/state',
'a//b',
'state?x=1',
'',
]) {
await expectLater(
session.get(op),
throwsA(
isA<LinkException>().having((e) => e.code, 'code', 'invalid'),
),
);
}
expect(requests, isEmpty);
});
test('an unreachable desktop is unavailable', () async {
final port = server.port;
await server.close(force: true);
final offline = LinkClientSession(
server: _record('http://127.0.0.1:$port'),
apiKey: 'key-1',
device: _device,
httpClient: (_) => HttpClient(),
ensureAccess: (_) async {},
);
addTearDown(offline.dispose);
await expectLater(
offline.get(LinkOps.state),
throwsA(
isA<LinkException>().having((e) => e.code, 'code', 'unavailable'),
),
);
});
});
group('WebSocket', () {
test('says hello, waits for welcome and relays messages', () async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(() => server.close(force: true));
final hello = Completer<Map<String, dynamic>>();
final fromPhone = StreamController<Map<String, dynamic>>();
addTearDown(fromPhone.close);
WebSocket? desktop;
String? authorization;
server.listen((request) async {
authorization = request.headers.value('authorization');
desktop = await WebSocketTransformer.upgrade(request);
desktop!.listen((data) {
final message = jsonDecode(data as String) as Map<String, dynamic>;
if (!hello.isCompleted) {
hello.complete(message);
desktop!.add(jsonEncode(_welcome));
} else {
fromPhone.add(message);
}
});
});
final timers = _Timers();
final session = LinkClientSession(
server: _record('http://127.0.0.1:${server.port}'),
apiKey: 'key-1',
device: _device,
httpClient: (_) => HttpClient(),
ensureAccess: (_) async {},
timer: timers.call,
);
addTearDown(session.dispose);
final states = <LinkConnectionState>[];
session.connectionStates.listen(states.add);
final messages = <Map<String, dynamic>>[];
session.messages.listen(messages.add);
session.start();
await session.connectionStates
.firstWhere((s) => s == LinkConnectionState.connected)
.timeout(const Duration(seconds: 5));
expect(authorization, 'Bearer key-1');
expect(await hello.future, {
'type': 'hello',
'deviceId': 'phone-1',
'name': 'Test phone',
'platform': 'ios',
'appVersion': '5.3.0',
'protocol': 1,
});
expect(states, [
LinkConnectionState.connecting,
LinkConnectionState.connected,
]);
desktop!.add(jsonEncode({'type': 'catalog.changed', 'version': 2}));
desktop!.add('not json');
desktop!.add(jsonEncode([1, 2]));
session.send({'type': 'player.state', 'state': <String, Object?>{}});
expect(await fromPhone.stream.first.timeout(const Duration(seconds: 5)), {
'type': 'player.state',
'state': <String, Object?>{},
});
await pumpEventQueue();
expect(messages, [
{'type': 'catalog.changed', 'version': 2},
]);
// The desktop going away schedules a retry after the shortest delay.
await desktop!.close();
await session.connectionStates
.firstWhere((s) => s == LinkConnectionState.disconnected)
.timeout(const Duration(seconds: 5));
await pumpEventQueue();
expect(timers.delays, [LinkClientSession.minBackoff]);
});
test('backs off from 1 s doubling to 30 s, then resets', () async {
final timers = _Timers();
var failures = 6;
final connects = <Uri>[];
final session = LinkClientSession(
server: _record('https://10.0.0.2:47710'),
apiKey: 'key-1',
device: _device,
ensureAccess: (_) async {},
timer: timers.call,
connectSocket: (uri, headers, client) async {
connects.add(uri);
expect(
headers['authorization'] ?? headers['Authorization'],
'Bearer key-1',
);
if (failures-- > 0) throw const SocketException('offline');
return _FakeSocket();
},
);
addTearDown(session.dispose);
session.start();
await pumpEventQueue();
for (var i = 0; i < 6; i++) {
expect(session.connectionState, LinkConnectionState.disconnected);
expect(session.issue, LinkSessionIssue.unreachable);
timers.last.fire();
await pumpEventQueue();
}
expect(timers.delays, const [
Duration(seconds: 1),
Duration(seconds: 2),
Duration(seconds: 4),
Duration(seconds: 8),
Duration(seconds: 16),
Duration(seconds: 30),
]);
expect(session.connectionState, LinkConnectionState.connected);
expect(session.issue, isNull);
expect(connects.first.toString(), 'wss://10.0.0.2:47710/mornye/v1/ws');
expect(connects, hasLength(7));
});
test('a dropped link retries after 1 s again', () async {
final timers = _Timers();
final sockets = <_FakeSocket>[];
final session = LinkClientSession(
server: _record('https://10.0.0.2:47710'),
apiKey: 'key-1',
device: _device,
ensureAccess: (_) async {},
timer: timers.call,
connectSocket: (_, _, _) async {
final socket = _FakeSocket();
sockets.add(socket);
return socket;
},
);
addTearDown(session.dispose);
session.start();
await pumpEventQueue();
expect(session.connectionState, LinkConnectionState.connected);
sockets.last.push({'type': 'open', 'url': 'x'});
sockets.last.serverClose();
await pumpEventQueue();
expect(session.connectionState, LinkConnectionState.disconnected);
expect(timers.delays, [LinkClientSession.minBackoff]);
timers.last.fire();
await pumpEventQueue();
expect(session.connectionState, LinkConnectionState.connected);
expect(sockets, hasLength(2));
});
test('pause closes the link and resume reconnects at once', () async {
final timers = _Timers();
final sockets = <_FakeSocket>[];
final session = LinkClientSession(
server: _record('https://10.0.0.2:47710'),
apiKey: 'key-1',
device: _device,
ensureAccess: (_) async {},
timer: timers.call,
connectSocket: (_, _, _) async {
final socket = _FakeSocket();
sockets.add(socket);
return socket;
},
);
addTearDown(session.dispose);
session.start();
await pumpEventQueue();
session.pause();
await pumpEventQueue();
expect(sockets.single.closed, isTrue);
expect(session.connectionState, LinkConnectionState.disconnected);
expect(timers.delays, isEmpty);
session.send({'type': 'player.state'});
session.reconnectNow();
await pumpEventQueue();
expect(sockets, hasLength(1));
session.resume();
await pumpEventQueue();
expect(session.connectionState, LinkConnectionState.connected);
expect(sockets, hasLength(2));
expect(sockets.first.sent.map((m) => m['type']), ['hello']);
});
test('reconnectNow skips the remaining backoff', () async {
final timers = _Timers();
var online = false;
final session = LinkClientSession(
server: _record('https://10.0.0.2:47710'),
apiKey: 'key-1',
device: _device,
ensureAccess: (_) async {},
timer: timers.call,
connectSocket: (_, _, _) async {
if (!online) throw const SocketException('offline');
return _FakeSocket();
},
);
addTearDown(session.dispose);
session.start();
await pumpEventQueue();
online = true;
session.reconnectNow();
await pumpEventQueue();
expect(session.connectionState, LinkConnectionState.connected);
expect(timers.last.isActive, isFalse);
});
test('a moved desktop reconnects at its new address', () async {
final connects = <Uri>[];
final session = LinkClientSession(
server: _record('https://10.0.0.2:47710'),
apiKey: 'key-1',
device: _device,
ensureAccess: (_) async {},
timer: _Timers().call,
connectSocket: (uri, _, _) async {
connects.add(uri);
return _FakeSocket();
},
);
addTearDown(session.dispose);
session.start();
await pumpEventQueue();
session.updateServer(_record('https://10.0.0.9:47711'));
await pumpEventQueue();
expect(session.server.address, 'https://10.0.0.9:47711');
expect(connects.map((u) => u.toString()), [
'wss://10.0.0.2:47710/mornye/v1/ws',
'wss://10.0.0.9:47711/mornye/v1/ws',
]);
expect(session.connectionState, LinkConnectionState.connected);
});
test('a refused key closes with 4401 and retries slowly', () async {
final timers = _Timers();
final session = LinkClientSession(
server: _record('https://10.0.0.2:47710'),
apiKey: 'key-1',
device: _device,
ensureAccess: (_) async {},
timer: timers.call,
connectSocket: (_, _, _) async =>
_FakeSocket(closeBeforeWelcome: linkCloseUnauthorized),
);
addTearDown(session.dispose);
session.start();
await pumpEventQueue();
expect(session.issue, LinkSessionIssue.unauthorized);
expect(timers.delays, [LinkClientSession.maxBackoff]);
});
test('an upgrade refused with 401 is unauthorized', () async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(() => server.close(force: true));
server.listen((request) async {
request.response.statusCode = 401;
await request.response.close();
});
final session = LinkClientSession(
server: _record('http://127.0.0.1:${server.port}'),
apiKey: 'revoked',
device: _device,
httpClient: (_) => HttpClient(),
ensureAccess: (_) async {},
timer: _Timers().call,
);
addTearDown(session.dispose);
session.start();
await session.connectionStates
.firstWhere((s) => s == LinkConnectionState.disconnected)
.timeout(const Duration(seconds: 5));
expect(session.issue, LinkSessionIssue.unauthorized);
});
test('a welcome of another protocol is incompatible', () async {
final session = LinkClientSession(
server: _record('https://10.0.0.2:47710'),
apiKey: 'key-1',
device: _device,
ensureAccess: (_) async {},
timer: _Timers().call,
connectSocket: (_, _, _) async =>
_FakeSocket(welcome: {..._welcome, 'protocol': 2}),
);
addTearDown(session.dispose);
session.start();
await pumpEventQueue();
expect(session.connectionState, LinkConnectionState.disconnected);
expect(session.issue, LinkSessionIssue.incompatible);
});
test('a missing welcome times out', () async {
final timers = _Timers();
final session = LinkClientSession(
server: _record('https://10.0.0.2:47710'),
apiKey: 'key-1',
device: _device,
ensureAccess: (_) async {},
timer: timers.call,
handshakeTimeout: const Duration(milliseconds: 50),
connectSocket: (_, _, _) async => _FakeSocket(welcome: null),
);
addTearDown(session.dispose);
session.start();
await session.connectionStates
.firstWhere((s) => s == LinkConnectionState.disconnected)
.timeout(const Duration(seconds: 5));
expect(session.issue, LinkSessionIssue.unreachable);
expect(timers.delays, [LinkClientSession.minBackoff]);
});
});
}
+95
View File
@@ -0,0 +1,95 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:mornye/services/link/client/link_client_store.dart';
import 'package:mornye/services/link/link_client_api.dart';
import 'package:shared_preferences/shared_preferences.dart';
LinkServerRecord _record(String id, {String address = 'https://10.0.0.2:1'}) =>
LinkServerRecord(
serverId: id,
name: 'Desktop $id',
connectionId: 'connection-$id',
address: address,
fingerprint: 'f' * 64,
);
void main() {
setUp(() => SharedPreferences.setMockInitialValues({}));
test('device id is a random UUID kept across stores', () async {
final first = await LinkClientStore().deviceId();
expect(
first,
matches(
RegExp(
r'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$',
),
),
);
expect(await LinkClientStore().deviceId(), first);
final preferences = await SharedPreferences.getInstance();
expect(preferences.getString(LinkClientStore.deviceIdKey), first);
});
test('records persist, replace by server id and keep order', () async {
final store = LinkClientStore();
await store.upsert(_record('a'));
await store.upsert(_record('b'));
await store.upsert(_record('a', address: 'https://10.0.0.9:2'));
final servers = await LinkClientStore().servers();
expect(servers.map((s) => s.serverId), ['a', 'b']);
expect(servers.first.address, 'https://10.0.0.9:2');
final preferences = await SharedPreferences.getInstance();
final raw = jsonDecode(preferences.getString(LinkClientStore.serversKey)!);
expect(raw, [
_record('a', address: 'https://10.0.0.9:2').toJson(),
_record('b').toJson(),
]);
});
test('address updates touch only the moved desktop', () async {
final store = LinkClientStore();
await store.upsert(_record('a'));
await store.upsert(_record('b'));
final servers = await store.updateAddress('b', 'https://10.0.0.7:47710');
expect(servers.map((s) => s.address), [
'https://10.0.0.2:1',
'https://10.0.0.7:47710',
]);
expect(servers.last.connectionId, 'connection-b');
expect(servers.last.fingerprint, 'f' * 64);
expect((await store.servers()).last.address, 'https://10.0.0.7:47710');
});
test('removing and the active choice persist', () async {
final store = LinkClientStore();
await store.upsert(_record('a'));
await store.upsert(_record('b'));
await store.setActiveServerId('b');
expect(await store.activeServerId(), 'b');
expect((await store.remove('a')).map((s) => s.serverId), ['b']);
await store.setActiveServerId(null);
expect(await store.activeServerId(), isNull);
});
test('broken or duplicate rows are skipped', () async {
SharedPreferences.setMockInitialValues({
LinkClientStore.serversKey: jsonEncode([
_record('a').toJson(),
{'serverId': 'b'},
_record('a', address: 'https://10.0.0.3:1').toJson(),
'junk',
]),
});
final servers = await LinkClientStore().servers();
expect(servers.map((s) => s.serverId), ['a']);
expect(servers.single.address, 'https://10.0.0.2:1');
SharedPreferences.setMockInitialValues({
LinkClientStore.serversKey: '{not json',
});
expect(await LinkClientStore().servers(), isEmpty);
});
}
+339
View File
@@ -0,0 +1,339 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mornye/l10n/l10n.dart';
import 'package:mornye/screens/settings/link_pairing_dialogs.dart';
import 'package:mornye/screens/settings/link_settings_page.dart';
import 'package:mornye/services/link/client/link_client_pairing.dart';
import 'package:mornye/theme/mornye_theme.dart';
import 'package:mornye/widgets/app_alert_dialog.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'support/link_client_fakes.dart';
final _l10n = lookupAppLocalizations(const Locale('en'));
Widget _app(Widget home, {bool mornye = false}) => MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
theme: mornye ? MornyeTheme.build(Brightness.light) : null,
home: home,
);
/// Opens [dialog] from a button and keeps what it popped in [results]. The
/// Mornye dialog chrome reads providers, hence the scope.
Widget _dialogHost(
Widget dialog,
List<Object?> results, {
bool mornye = false,
}) => ProviderScope(
child: _app(
mornye: mornye,
Builder(
builder: (context) => Scaffold(
body: Center(
child: TextButton(
onPressed: () async => results.add(
await showAppDialog<Object?>(
context: context,
builder: (_) => dialog,
),
),
child: const Text('open'),
),
),
),
),
),
);
Future<void> _settle(WidgetTester tester) async {
// Spinners never settle; pump past the dialog and snack bar transitions.
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
}
void main() {
group('PIN dialog', () {
for (final mornye in [false, true]) {
final style = mornye ? 'Mornye' : 'Material';
testWidgets('$style: enables Pair at six digits and shows errors', (
tester,
) async {
final pins = <String>[];
final answers = [LinkPairingError.badPin, null];
final results = <Object?>[];
await tester.pumpWidget(
_dialogHost(
LinkPinDialog(
serverName: 'Studio PC',
shortFingerprint: 'ab12cd34',
pairingOpen: true,
onSubmit: (pin) async {
pins.add(pin);
return answers.removeAt(0);
},
),
results,
mornye: mornye,
),
);
await tester.tap(find.text('open'));
await _settle(tester);
expect(find.text(_l10n.linkPinTitle('Studio PC')), findsOneWidget);
expect(find.text(_l10n.linkPinCode('ab12cd34')), findsOneWidget);
expect(find.text(_l10n.linkPinNotOpen), findsNothing);
final field = find.byKey(LinkPinDialog.fieldKey);
await tester.enterText(field, 'ab12');
await tester.pump();
expect(
tester
.widget<EditableText>(find.byType(EditableText))
.controller
.text,
'12',
);
await tester.tap(find.text(_l10n.linkPair));
await tester.pump();
expect(pins, isEmpty);
await tester.enterText(field, '1234567');
await tester.pump();
await tester.tap(find.text(_l10n.linkPair));
await _settle(tester);
expect(pins, ['123456']);
expect(find.text(_l10n.linkErrorBadPin), findsOneWidget);
expect(
tester
.widget<EditableText>(find.byType(EditableText))
.controller
.text,
isEmpty,
);
await tester.enterText(field, '654321');
await tester.pump();
await tester.tap(find.text(_l10n.linkPair));
await _settle(tester);
expect(pins, ['123456', '654321']);
expect(results, [true]);
expect(find.byType(LinkPinDialog), findsNothing);
});
}
testWidgets('says when the computer is not ready to pair', (tester) async {
final results = <Object?>[];
await tester.pumpWidget(
_dialogHost(
LinkPinDialog(
serverName: 'Studio PC',
shortFingerprint: 'ab12cd34',
pairingOpen: false,
onSubmit: (_) async => LinkPairingError.pairingClosed,
),
results,
),
);
await tester.tap(find.text('open'));
await _settle(tester);
expect(find.text(_l10n.linkPinNotOpen), findsOneWidget);
await tester.enterText(find.byKey(LinkPinDialog.fieldKey), '123456');
await tester.pump();
await tester.tap(find.text(_l10n.linkPair));
await _settle(tester);
expect(find.text(_l10n.linkErrorPairingClosed), findsOneWidget);
await tester.tap(find.text(_l10n.dialogCancel));
await _settle(tester);
expect(results, [false]);
});
test('every pairing error has its own message', () {
final messages = {
for (final error in LinkPairingError.values)
error: linkPairingErrorMessage(_l10n, error),
};
expect(messages.values.every((m) => m.isNotEmpty), isTrue);
expect(
messages.values.toSet(),
hasLength(LinkPairingError.values.length),
);
expect(
messages[LinkPairingError.tooManyAttempts],
_l10n.linkErrorTooManyAttempts,
);
expect(
messages[LinkPairingError.certificateMismatch],
_l10n.linkErrorCertificate,
);
});
});
group('manual address', () {
test('accepts hosts, host:port, URLs and IPv6', () {
expect(linkParseManualAddress(' 192.168.1.20 ', '47710'), (
host: '192.168.1.20',
port: 47710,
));
expect(linkParseManualAddress('studio.local:5000', '47710'), (
host: 'studio.local',
port: 5000,
));
expect(linkParseManualAddress('https://10.0.0.2:47711/mornye', '1'), (
host: '10.0.0.2',
port: 47711,
));
expect(linkParseManualAddress('[fe80::2]:47712', '1'), (
host: 'fe80::2',
port: 47712,
));
expect(linkParseManualAddress('fe80::2', '47710'), (
host: 'fe80::2',
port: 47710,
));
});
test('refuses what is not an address', () {
for (final (host, port) in [
('', '47710'),
('10.0.0.2', ''),
('10.0.0.2', '0'),
('10.0.0.2', '70000'),
('my computer', '47710'),
('user@10.0.0.2', '47710'),
('not:an:address', '47710'),
]) {
expect(linkParseManualAddress(host, port), isNull, reason: host);
}
});
for (final mornye in [false, true]) {
testWidgets('${mornye ? 'Mornye' : 'Material'}: dialog checks input', (
tester,
) async {
final results = <Object?>[];
await tester.pumpWidget(
_dialogHost(const LinkManualAddDialog(), results, mornye: mornye),
);
await tester.tap(find.text('open'));
await _settle(tester);
await tester.enterText(
find.byKey(LinkManualAddDialog.hostKey),
'my computer',
);
await tester.tap(find.text(_l10n.linkContinue));
await tester.pump();
expect(find.text(_l10n.linkErrorInvalidAddress), findsOneWidget);
await tester.enterText(
find.byKey(LinkManualAddDialog.hostKey),
'10.0.0.5:5000',
);
await tester.tap(find.text(_l10n.linkContinue));
await _settle(tester);
expect(results, [(host: '10.0.0.5', port: 5000)]);
});
}
});
group('page', () {
setUp(() => SharedPreferences.setMockInitialValues({}));
Future<LinkClientHarness> pumpPage(
WidgetTester tester, {
bool mornye = false,
bool localNetworkAllowed = true,
bool onWifi = true,
}) async {
final harness = LinkClientHarness()
..localNetworkAllowed = localNetworkAllowed
..onWifi = onWifi;
await tester.pumpWidget(
ProviderScope(
overrides: harness.overrides,
child: _app(const LinkSettingsPage(), mornye: mornye),
),
);
await _settle(tester);
return harness;
}
for (final mornye in [false, true]) {
testWidgets(
'${mornye ? 'Mornye' : 'Material'}: pairs a nearby computer',
(tester) async {
final harness = await pumpPage(tester, mornye: mornye);
expect(find.text(_l10n.linkSearching), findsOneWidget);
expect(harness.browser.started, 1);
harness.pairing.targets['10.0.0.3'] = linkTestTarget(
'b',
host: '10.0.0.3',
);
harness.browser.resolve('b', '10.0.0.3');
await _settle(tester);
expect(find.text('Desktop b'), findsOneWidget);
await tester.tap(find.text('Desktop b'));
await _settle(tester);
expect(
harness.pairing.probes.single.expectedFingerprint,
linkTestFingerprint('b'),
);
await tester.enterText(find.byKey(LinkPinDialog.fieldKey), '123456');
await tester.pump();
await tester.tap(find.text(_l10n.linkPair));
await _settle(tester);
expect(harness.pairing.pins, ['123456']);
expect(find.byType(LinkPinDialog), findsNothing);
expect(find.text(_l10n.linkPaired('Desktop b')), findsOneWidget);
expect(find.text(_l10n.linkPairedSection), findsOneWidget);
expect(harness.sessions.single.server.serverId, 'b');
// Leaving the page stops discovery.
await tester.pumpWidget(const SizedBox());
await tester.pump();
},
);
}
testWidgets('warns when the certificate does not match', (tester) async {
final harness = await pumpPage(tester);
harness.pairing.probeError = LinkPairingError.certificateMismatch;
harness.browser.resolve('b', '10.0.0.3');
await _settle(tester);
await tester.tap(find.text('Desktop b'));
await _settle(tester);
expect(find.text(_l10n.linkErrorCertificateTitle), findsOneWidget);
expect(find.text(_l10n.linkErrorCertificate), findsOneWidget);
expect(find.byType(LinkPinDialog), findsNothing);
await tester.pumpWidget(const SizedBox());
await tester.pump();
});
testWidgets('asks for local network access', (tester) async {
final harness = await pumpPage(tester, localNetworkAllowed: false);
expect(find.text(_l10n.linkLocalNetworkTitle), findsOneWidget);
expect(harness.browser.started, 0);
await tester.tap(find.text(_l10n.linkLocalNetworkAllow));
await _settle(tester);
expect(find.text(_l10n.networkErrorLocalPermission), findsOneWidget);
harness.localNetworkAllowed = true;
await tester.tap(find.text(_l10n.linkLocalNetworkAllow));
await _settle(tester);
expect(harness.browser.started, 1);
expect(find.text(_l10n.linkLocalNetworkTitle), findsNothing);
await tester.pumpWidget(const SizedBox());
await tester.pump();
});
testWidgets('says when Wi-Fi is off', (tester) async {
await pumpPage(tester, onWifi: false);
expect(find.text(_l10n.linkWifiOffTitle), findsOneWidget);
await tester.pumpWidget(const SizedBox());
await tester.pump();
});
});
}
+266
View File
@@ -0,0 +1,266 @@
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/misc.dart' show Override;
import 'package:mornye/services/link/client/link_client_controller.dart';
import 'package:mornye/services/link/client/link_client_discovery.dart';
import 'package:mornye/services/link/client/link_client_library.dart';
import 'package:mornye/services/link/client/link_client_pairing.dart';
import 'package:mornye/services/link/client/link_client_session.dart';
import 'package:mornye/services/link/client/link_client_store.dart';
import 'package:mornye/services/link/link_client_api.dart';
import 'package:mornye/services/link/link_protocol.dart';
import 'package:mornye/services/local_network_access.dart';
import 'package:mornye/services/network_storage_service.dart';
/// A stable fake certificate fingerprint per server id.
String linkTestFingerprint(String serverId) =>
serverId.codeUnitAt(0).toRadixString(16).padLeft(2, '0') * 32;
LinkPairingTarget linkTestTarget(
String serverId, {
String host = '10.0.0.2',
bool pairing = true,
}) => LinkPairingTarget(
address: 'https://$host:47710',
info: LinkServerInfo(
serverId: serverId,
name: 'Desktop $serverId',
protocol: linkProtocolVersion,
appVersion: '5.3.0',
fingerprint: linkTestFingerprint(serverId),
pairing: pairing,
),
);
class FakeLinkSession implements LinkSession {
FakeLinkSession(this.server, this.apiKey);
@override
LinkServerRecord server;
final String apiKey;
final _states = StreamController<LinkConnectionState>.broadcast();
final _messages = StreamController<Map<String, dynamic>>.broadcast();
final calls = <String>[];
bool disposed = false;
@override
LinkConnectionState connectionState = LinkConnectionState.disconnected;
@override
LinkSessionIssue? issue;
void emit(LinkConnectionState state, [LinkSessionIssue? reason]) {
connectionState = state;
issue = reason;
_states.add(state);
}
void push(Map<String, dynamic> message) => _messages.add(message);
@override
Stream<LinkConnectionState> get connectionStates => _states.stream;
@override
Stream<Map<String, dynamic>> get messages => _messages.stream;
@override
void send(Map<String, dynamic> message) => calls.add('send');
@override
Future<Object?> get(String op, [Map<String, String> query = const {}]) =>
throw UnimplementedError();
@override
Future<Object?> post(String op, Map<String, dynamic> body) =>
throw UnimplementedError();
@override
void start() => calls.add('start');
@override
void pause() => calls.add('pause');
@override
void resume() => calls.add('resume');
@override
void reconnectNow() => calls.add('reconnect');
@override
void updateServer(LinkServerRecord server) {
this.server = server;
calls.add('update ${server.address}');
}
@override
Future<void> dispose() async {
disposed = true;
await _states.close();
await _messages.close();
}
}
class FakeLinkBrowser implements LinkServiceBrowser {
StreamController<LinkServiceEvent>? events;
int started = 0;
int stopped = 0;
@override
Future<Stream<LinkServiceEvent>> start() async {
started++;
events = StreamController<LinkServiceEvent>();
return events!.stream;
}
@override
Future<void> stop() async {
stopped++;
unawaited(events?.close());
events = null;
}
/// A desktop advertising [serverId] at [host].
void resolve(String serverId, String host, {String? fingerprint}) =>
events!.add(
LinkServiceResolved(
name: 'Desktop $serverId',
port: 47710,
addresses: [host],
attributes: {
'v': '1',
'id': serverId,
'fp': fingerprint ?? linkTestFingerprint(serverId),
},
),
);
}
class FakeLinkBridge implements LinkLibraryBridge {
final connections = <String, NetworkConnection>{};
final calls = <String>[];
@override
Future<NetworkConnection?> connection(String connectionId) async =>
connections[connectionId];
@override
Future<void> saveConnection(NetworkConnection connection) async {
connections[connection.id] = connection;
calls.add('save ${connection.id}');
}
@override
Future<void> updateAddress(String connectionId, String address) async =>
calls.add('address $connectionId $address');
@override
Future<void> addLibrarySource(NetworkConnection connection) async =>
calls.add('source ${connection.id}');
@override
Future<void> rescan(String connectionId) async =>
calls.add('rescan $connectionId');
@override
Future<void> removeConnection(String connectionId) async {
connections.remove(connectionId);
calls.add('remove $connectionId');
}
}
class FakeLinkPairing implements LinkPairingApi {
/// Desktops [probe] finds, by host.
final targets = <String, LinkPairingTarget>{};
final probes = <({Uri address, String? expectedFingerprint})>[];
final pins = <String>[];
final devices = <LinkDeviceIdentity>[];
String key = 'key-1';
LinkPairingError? probeError;
LinkPairingError? error;
@override
Future<LinkPairingTarget> probe(
Uri address, {
String? expectedFingerprint,
}) async {
probes.add((address: address, expectedFingerprint: expectedFingerprint));
if (probeError case final error?) throw LinkPairingException(error);
final target = targets[address.host];
if (target == null) {
throw const LinkPairingException(LinkPairingError.unreachable);
}
return target;
}
@override
Future<LinkPairingResult> pair(
LinkPairingTarget target, {
required String pin,
required LinkDeviceIdentity device,
}) async {
pins.add(pin);
devices.add(device);
if (error case final error?) throw LinkPairingException(error);
return LinkPairingResult(
apiKey: key,
serverId: target.info.serverId,
name: target.info.name,
fingerprint: target.fingerprint,
);
}
}
/// The client's providers wired to fakes. Tests set
/// `SharedPreferences.setMockInitialValues` first.
class LinkClientHarness {
LinkClientHarness({this.supported = true});
final bool supported;
final browser = FakeLinkBrowser();
final bridge = FakeLinkBridge();
final pairing = FakeLinkPairing();
final sessions = <FakeLinkSession>[];
bool localNetworkAllowed = true;
bool onWifi = true;
List<Override> get overrides => [
linkClientSupportedProvider.overrideWithValue(supported),
linkClientEnvironmentProvider.overrideWithValue(
LinkClientEnvironment(
deviceName: () async => 'Test phone',
platform: 'android',
appVersion: '5.3.0',
createBrowser: () => browser,
createSession: (server, apiKey, device) {
final session = FakeLinkSession(server, apiKey);
sessions.add(session);
return session;
},
ensureLocalNetwork: () async {
if (!localNetworkAllowed) {
throw const LocalNetworkPermissionException();
}
},
onLocalNetwork: () async => onWifi,
),
),
linkClientStoreProvider.overrideWithValue(LinkClientStore()),
linkPairingApiProvider.overrideWithValue(pairing),
linkLibraryBridgeProvider.overrideWithValue(bridge),
];
late final container = ProviderContainer(overrides: overrides);
LinkClientController get controller =>
container.read(linkClientControllerProvider.notifier);
LinkClientState get state => container.read(linkClientControllerProvider);
LinkClientApi? get active => container.read(linkActiveClientProvider);
/// Keeps the controller alive, as the app root does, and waits for it to
/// load.
Future<void> start() async {
container.listen(linkClientControllerProvider, (_, _) {});
await controller.ready;
}
}
@@ -8,6 +8,7 @@
#include <app_links/app_links_plugin_c_api.h>
#include <audioplayers_windows/audioplayers_windows_plugin.h>
#include <bonsoir_windows/bonsoir_windows_plugin_c_api.h>
#include <connectivity_plus/connectivity_plus_windows_plugin.h>
#include <desktop_drop/desktop_drop_plugin.h>
#include <dynamic_color/dynamic_color_plugin_c_api.h>
@@ -24,6 +25,8 @@ void RegisterPlugins(flutter::PluginRegistry* registry) {
registry->GetRegistrarForPlugin("AppLinksPluginCApi"));
AudioplayersWindowsPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("AudioplayersWindowsPlugin"));
BonsoirWindowsPluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("BonsoirWindowsPluginCApi"));
ConnectivityPlusWindowsPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("ConnectivityPlusWindowsPlugin"));
DesktopDropPluginRegisterWithRegistrar(
+1
View File
@@ -5,6 +5,7 @@
list(APPEND FLUTTER_PLUGIN_LIST
app_links
audioplayers_windows
bonsoir_windows
connectivity_plus
desktop_drop
dynamic_color