From 32fc942a043ab45aa763ceb040ef0c61eb501705 Mon Sep 17 00:00:00 2001
From: zarzet <42882290+zarzet@users.noreply.github.com>
Date: Sun, 25 Oct 2026 02:37:07 +0700
Subject: [PATCH] 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.
---
android/app/src/main/AndroidManifest.xml | 2 +
ios/Runner/Info.plist | 4 +
lib/l10n/arb/app_en.arb | 231 +++++++
lib/l10n/arb/app_id.arb | 51 +-
.../settings/link_pairing_dialogs.dart | 404 ++++++++++++
lib/screens/settings/link_settings_page.dart | 417 ++++++++++++
lib/screens/settings/settings_tab.dart | 18 +
.../link/client/link_client_bonsoir.dart | 66 ++
.../link/client/link_client_controller.dart | 620 ++++++++++++++++++
.../link/client/link_client_discovery.dart | 262 ++++++++
.../link/client/link_client_http.dart | 205 ++++++
.../link/client/link_client_library.dart | 149 +++++
.../link/client/link_client_pairing.dart | 276 ++++++++
.../link/client/link_client_session.dart | 470 +++++++++++++
.../link/client/link_client_store.dart | 125 ++++
macos/Flutter/GeneratedPluginRegistrant.swift | 2 +
pubspec.lock | 48 ++
pubspec.yaml | 2 +
test/link_client_controller_test.dart | 364 ++++++++++
test/link_client_discovery_test.dart | 188 ++++++
test/link_client_pairing_test.dart | 354 ++++++++++
test/link_client_session_test.dart | 564 ++++++++++++++++
test/link_client_store_test.dart | 95 +++
test/link_settings_page_test.dart | 339 ++++++++++
test/support/link_client_fakes.dart | 266 ++++++++
.../flutter/generated_plugin_registrant.cc | 3 +
windows/flutter/generated_plugins.cmake | 1 +
27 files changed, 5525 insertions(+), 1 deletion(-)
create mode 100644 lib/screens/settings/link_pairing_dialogs.dart
create mode 100644 lib/screens/settings/link_settings_page.dart
create mode 100644 lib/services/link/client/link_client_bonsoir.dart
create mode 100644 lib/services/link/client/link_client_controller.dart
create mode 100644 lib/services/link/client/link_client_discovery.dart
create mode 100644 lib/services/link/client/link_client_http.dart
create mode 100644 lib/services/link/client/link_client_library.dart
create mode 100644 lib/services/link/client/link_client_pairing.dart
create mode 100644 lib/services/link/client/link_client_session.dart
create mode 100644 lib/services/link/client/link_client_store.dart
create mode 100644 test/link_client_controller_test.dart
create mode 100644 test/link_client_discovery_test.dart
create mode 100644 test/link_client_pairing_test.dart
create mode 100644 test/link_client_session_test.dart
create mode 100644 test/link_client_store_test.dart
create mode 100644 test/link_settings_page_test.dart
create mode 100644 test/support/link_client_fakes.dart
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 8048f0d66..dd9d33df4 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -13,6 +13,8 @@
+
+
NSLocalNetworkUsageDescription
Connect to your music servers and network storage to browse and play your music.
+ NSBonjourServices
+
+ _mornye._tcp
+
NSAppTransportSecurity
NSAllowsArbitraryLoads
diff --git a/lib/l10n/arb/app_en.arb b/lib/l10n/arb/app_en.arb
index 43638fd1b..a90b5eaf4 100644
--- a/lib/l10n/arb/app_en.arb
+++ b/lib/l10n/arb/app_en.arb
@@ -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"
+ }
+ }
}
}
diff --git a/lib/l10n/arb/app_id.arb b/lib/l10n/arb/app_id.arb
index 98381d41e..6bd876c27 100644
--- a/lib/l10n/arb/app_id.arb
+++ b/lib/l10n/arb/app_id.arb
@@ -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."
}
diff --git a/lib/screens/settings/link_pairing_dialogs.dart b/lib/screens/settings/link_pairing_dialogs.dart
new file mode 100644
index 000000000..209dd6fcd
--- /dev/null
+++ b/lib/screens/settings/link_pairing_dialogs.dart
@@ -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 Function(String pin) onSubmit;
+
+ @override
+ State createState() => _LinkPinDialogState();
+}
+
+class _LinkPinDialogState extends State {
+ 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 _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 createState() => _LinkManualAddDialogState();
+}
+
+class _LinkManualAddDialogState extends State {
+ 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 createState() => _LinkForgetDialogState();
+}
+
+class _LinkForgetDialogState extends State {
+ 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),
+ ),
+ ],
+ );
+ }
+}
diff --git a/lib/screens/settings/link_settings_page.dart b/lib/screens/settings/link_settings_page.dart
new file mode 100644
index 000000000..2a3f3a386
--- /dev/null
+++ b/lib/screens/settings/link_settings_page.dart
@@ -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 createState() => _LinkSettingsPageState();
+}
+
+class _LinkSettingsPageState extends ConsumerState {
+ 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 _showCertificateWarning() => showAppDialog(
+ 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 _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(
+ 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 _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 _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 _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 _forget(LinkServerRecord record) async {
+ final removeLibrary = await showAppDialog(
+ context: context,
+ builder: (_) => LinkForgetDialog(name: record.name),
+ );
+ if (removeLibrary == null || !mounted) return;
+ await _controller.forget(record.serverId, removeLibrary: removeLibrary);
+ }
+
+ Future _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 _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,
+ );
+}
diff --git a/lib/screens/settings/settings_tab.dart b/lib/screens/settings/settings_tab.dart
index 9faeeb0c9..f697b3ad5 100644
--- a/lib/screens/settings/settings_tab.dart
+++ b/lib/screens/settings/settings_tab.dart
@@ -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 {
],
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,
diff --git a/lib/services/link/client/link_client_bonsoir.dart b/lib/services/link/client/link_client_bonsoir.dart
new file mode 100644
index 000000000..a4660de36
--- /dev/null
+++ b/lib/services/link/client/link_client_bonsoir.dart
@@ -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? _subscription;
+ StreamController? _events;
+
+ @override
+ Future> start() async {
+ await stop();
+ final discovery = _discovery = BonsoirDiscovery(
+ type: linkServiceType,
+ printLogs: false,
+ );
+ _events = StreamController();
+ 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 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();
+ }
+ }
+}
diff --git a/lib/services/link/client/link_client_controller.dart b/lib/services/link/client/link_client_controller.dart
new file mode 100644
index 000000000..70838c801
--- /dev/null
+++ b/lib/services/link/client/link_client_controller.dart
@@ -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(
+ (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 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 Function() ensureLocalNetwork;
+
+ /// Whether Wi-Fi or Ethernet is connected.
+ final Future 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 _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 _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(
+ (ref) => LinkClientEnvironment.device(),
+);
+
+final linkClientStoreProvider = Provider(
+ (ref) => LinkClientStore(),
+);
+
+final linkPairingApiProvider = Provider(
+ (ref) => LinkPairingClient(),
+);
+
+final linkLibraryBridgeProvider = Provider(
+ 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 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 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 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? servers,
+ String? activeServerId,
+ bool clearActiveServer = false,
+ LinkConnectionState? connection,
+ LinkSessionIssue? issue,
+ bool clearIssue = false,
+ List? 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 {
+ /// How long `catalog.changed` bursts settle before a rescan.
+ static const rescanDelay = Duration(seconds: 2);
+
+ LinkSession? _session;
+ StreamSubscription? _stateSubscription;
+ StreamSubscription