Files
SpotiFLAC-Mobile/test/link_client_controller_test.dart
T
zarzet 32fc942a04 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.
2026-10-25 02:37:07 +07:00

365 lines
13 KiB
Dart

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);
});
}