feat(link): add computer library visibility toggle

This commit is contained in:
zarzet committed 2026-11-06 21:27:48 +07:00
1 parent 7cfd5f661e
commit b889dabbb4
9 files changed
+352 -20

No files matched your search

+17
View File
@@ -9597,6 +9597,14 @@
"@linkShareSongsSubtitle": {
"description": "Switch subtitle for showing this phone's songs on the computer"
},
"linkShowComputerSongsTitle": "Show computer songs in Library",
"@linkShowComputerSongsTitle": {
"description": "Switch title: songs from paired computers appear in this phone's Library"
},
"linkShowComputerSongsSubtitle": "Hide songs from paired computers without disconnecting Mornye Link. Songs saved to this phone stay in Library.",
"@linkShowComputerSongsSubtitle": {
"description": "Switch subtitle: hiding computer songs preserves the Link connection and songs saved on the phone"
},
"linkFollowDesktopTitle": "Follow the computer's playback",
"@linkFollowDesktopTitle": {
"description": "Switch title: the phone's player shows the computer when the computer starts playing"
@@ -9725,6 +9733,15 @@
}
}
},
"linkPairedWithoutLibrary": "Paired with {name}. Computer songs stay hidden from Library.",
"@linkPairedWithoutLibrary": {
"description": "Message after pairing succeeded while computer songs are hidden from this phone's Library",
"placeholders": {
"name": {
"type": "String"
}
}
},
"linkPairAgain": "Pair again",
"@linkPairAgain": {
"description": "Action that repeats pairing with a computer that no longer accepts this phone"
+14 -1
View File
@@ -127,7 +127,11 @@ class _LinkSettingsPageState extends ConsumerState<LinkSettingsPage> {
),
);
if (paired == true && mounted) {
_showMessage(context.l10n.linkPaired(serverName));
_showMessage(
ref.read(linkPhoneOptionsProvider).showComputerSongs
? context.l10n.linkPaired(serverName)
: context.l10n.linkPairedWithoutLibrary(serverName),
);
}
}
@@ -329,6 +333,15 @@ class _LinkSettingsPageState extends ConsumerState<LinkSettingsPage> {
...settingsSectionSlivers(
title: l10n.linkPhoneSection,
children: [
SettingsSwitchItem(
icon: Icons.computer,
title: l10n.linkShowComputerSongsTitle,
subtitle: l10n.linkShowComputerSongsSubtitle,
value: options.showComputerSongs,
onChanged: options.loaded
? optionsNotifier.setShowComputerSongs
: null,
),
SettingsSwitchItem(
icon: Icons.library_music_outlined,
title: l10n.linkShareSongsTitle,
@@ -14,6 +14,7 @@ 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/features/link_phone_options.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';
@@ -261,6 +262,8 @@ class LinkClientController extends Notifier<LinkClientState> {
ref.read(linkClientEnvironmentProvider);
LinkClientStore get _store => ref.read(linkClientStoreProvider);
LinkLibraryBridge get _library => ref.read(linkLibraryBridgeProvider);
bool get _showComputerSongs =>
ref.read(linkPhoneOptionsProvider).showComputerSongs;
/// Completes once paired desktops are loaded and the session started.
Future<void> ensureLoaded() => _loading ?? Future.value();
@@ -287,6 +290,20 @@ class LinkClientController extends Notifier<LinkClientState> {
(_, keep) => _updateConnected(() => _keepConnected = keep),
fireImmediately: true,
);
ref.listen(linkPhoneOptionsProvider, (previous, next) {
if (!next.loaded ||
previous?.loaded != true ||
previous?.showComputerSongs == next.showComputerSongs) {
return;
}
_rescan?.cancel();
unawaited(
_serial(_syncLibrarySources).catchError(
(Object error) =>
_log.w('Updating computer songs in Library failed: $error'),
),
);
});
ref.onDispose(_dispose);
_loading = Future<void>.microtask(
() => _serial(_load).catchError(
@@ -304,6 +321,8 @@ class LinkClientController extends Notifier<LinkClientState> {
}
Future<void> _load() async {
await ref.read(linkPhoneOptionsProvider.notifier).ensureLoaded();
if (_disposed) return;
final store = _store;
final servers = await store.servers();
var active = await store.activeServerId();
@@ -317,7 +336,21 @@ class LinkClientController extends Notifier<LinkClientState> {
activeServerId: active,
clearActiveServer: active == null,
);
await _restartSession();
if (!_showComputerSongs) await _syncLibrarySources();
if (!_disposed) await _restartSession();
}
Future<void> _syncLibrarySources() async {
if (_disposed) return;
final enabled = _showComputerSongs;
for (final server in state.servers) {
if (_disposed) return;
try {
await _library.setLibrarySourceEnabled(server.connectionId, enabled);
} on Object catch (error) {
_log.w('Updating ${server.name} songs in Library failed: $error');
}
}
}
Future<LinkDeviceIdentity> _identity() async {
@@ -427,9 +460,11 @@ class LinkClientController extends Notifier<LinkClientState> {
void _scheduleRescan(LinkSession session) {
final connectionId = session.server.connectionId;
_rescan?.cancel();
if (!_showComputerSongs) return;
_rescan = Timer(rescanDelay, () {
_rescan = null;
if (_disposed ||
!_showComputerSongs ||
!identical(session, _session) ||
session.connectionState != LinkConnectionState.connected) {
return;
@@ -770,8 +805,8 @@ class LinkClientController extends Notifier<LinkClientState> {
});
/// 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].
/// Subsonic network connection and, when enabled, 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)
@@ -813,12 +848,17 @@ class LinkClientController extends Notifier<LinkClientState> {
return (record, connection);
});
unawaited(
_library
.addLibrarySource(connection)
.catchError(
(Object error) =>
_log.w('Adding the computer to Library failed: $error'),
),
_serial(() async {
if (_disposed) return;
if (_showComputerSongs) {
await _library.addLibrarySource(connection);
} else {
await _library.setLibrarySourceEnabled(connection.id, false);
}
}).catchError(
(Object error) =>
_log.w('Adding the computer to Library failed: $error'),
),
);
return record;
}
@@ -27,6 +27,9 @@ abstract interface class LinkLibraryBridge {
/// storage screen does after adding a Subsonic server.
Future<void> addLibrarySource(NetworkConnection connection);
/// Shows or hides the indexed songs, keeping the network connection.
Future<void> setLibrarySourceEnabled(String connectionId, bool enabled);
/// Rescans the connection's Library source incrementally, after any
/// running scan.
Future<void> rescan(String connectionId);
@@ -107,6 +110,26 @@ class LinkNetworkLibraryBridge implements LinkLibraryBridge {
_scan(source.id);
}
@override
Future<void> setLibrarySourceEnabled(
String connectionId,
bool enabled,
) async {
if (enabled) {
final saved = await connection(connectionId);
if (saved != null && _ref.mounted) await addLibrarySource(saved);
return;
}
final source = await _database.getSourceByPath(_rootSource(connectionId));
if (!_ref.mounted || source == null) return;
_pendingScans.remove(source.id);
if (source.enabled) {
await _ref
.read(localLibraryProvider.notifier)
.setSourceEnabled(source.id, false);
}
}
@override
Future<void> rescan(String connectionId) async {
final source = await _database.getSourceByPath(_rootSource(connectionId));
@@ -13,6 +13,7 @@ class LinkPhoneOptions {
const LinkPhoneOptions({
this.loaded = false,
this.shareSongs = true,
this.showComputerSongs = true,
this.followDesktop = true,
});
@@ -22,15 +23,22 @@ class LinkPhoneOptions {
/// This phone's songs show in the computer's Library and play there.
final bool shareSongs;
/// Paired computers' songs show in this phone's Library.
final bool showComputerSongs;
/// The player screens follow the computer when it starts playing.
final bool followDesktop;
LinkPhoneOptions copyWith({bool? shareSongs, bool? followDesktop}) =>
LinkPhoneOptions(
loaded: true,
shareSongs: shareSongs ?? this.shareSongs,
followDesktop: followDesktop ?? this.followDesktop,
);
LinkPhoneOptions copyWith({
bool? shareSongs,
bool? showComputerSongs,
bool? followDesktop,
}) => LinkPhoneOptions(
loaded: true,
shareSongs: shareSongs ?? this.shareSongs,
showComputerSongs: showComputerSongs ?? this.showComputerSongs,
followDesktop: followDesktop ?? this.followDesktop,
);
}
/// Keeps [LinkPhoneOptions] in shared preferences. Tests pass [initial],
@@ -39,14 +47,18 @@ class LinkPhoneOptionsNotifier extends Notifier<LinkPhoneOptions> {
LinkPhoneOptionsNotifier({this.initial});
static const shareSongsKey = 'link_phone_share_songs';
static const showComputerSongsKey = 'link_phone_show_computer_songs';
static const followDesktopKey = 'link_phone_follow_desktop';
final LinkPhoneOptions? initial;
Future<void>? _loading;
Future<void> ensureLoaded() => _loading ?? Future.value();
@override
LinkPhoneOptions build() {
if (initial case final options?) return options;
unawaited(_restore());
_loading = _restore();
return const LinkPhoneOptions();
}
@@ -57,6 +69,7 @@ class LinkPhoneOptionsNotifier extends Notifier<LinkPhoneOptions> {
options = LinkPhoneOptions(
loaded: true,
shareSongs: prefs.getBool(shareSongsKey) ?? true,
showComputerSongs: prefs.getBool(showComputerSongsKey) ?? true,
followDesktop: prefs.getBool(followDesktopKey) ?? true,
);
} on Object catch (error) {
@@ -71,6 +84,11 @@ class LinkPhoneOptionsNotifier extends Notifier<LinkPhoneOptions> {
unawaited(_persist((prefs) => prefs.setBool(shareSongsKey, share)));
}
void setShowComputerSongs(bool show) {
state = state.copyWith(showComputerSongs: show);
unawaited(_persist((prefs) => prefs.setBool(showComputerSongsKey, show)));
}
void setFollowDesktop(bool follow) {
state = state.copyWith(followDesktop: follow);
unawaited(_persist((prefs) => prefs.setBool(followDesktopKey, follow)));
+137
View File
@@ -8,6 +8,7 @@ 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/features/link_phone_options.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';
@@ -140,6 +141,142 @@ void main() {
expect(harness.active, same(harness.sessions.last));
});
test(
'hiding computer songs keeps all pairings and the active session',
() async {
final harness = await _started();
final a = await harness.controller.pair(linkTestTarget('a'), '123456');
final b = await harness.controller.pair(linkTestTarget('b'), '123456');
await pumpEventQueue();
final session = harness.sessions.single;
final options = harness.container.read(linkPhoneOptionsProvider.notifier);
options.setShowComputerSongs(false);
await pumpEventQueue();
expect(harness.bridge.librarySources, {
a.connectionId: false,
b.connectionId: false,
});
expect(harness.bridge.connections, hasLength(2));
expect(harness.state.servers, hasLength(2));
expect(harness.active, same(session));
expect(session.disposed, isFalse);
expect(
harness.container.read(linkPhoneOptionsProvider).shareSongs,
isTrue,
);
options.setShowComputerSongs(true);
await pumpEventQueue();
expect(harness.bridge.librarySources.values, everyElement(isTrue));
expect(harness.active, same(session));
expect(harness.sessions, hasLength(1));
},
);
test(
'saved hidden songs stay hidden through pairing and catalog changes',
() async {
SharedPreferences.setMockInitialValues({
LinkPhoneOptionsNotifier.showComputerSongsKey: false,
});
final harness = await _started();
final record = await harness.controller.pair(
linkTestTarget('a'),
'123456',
);
await pumpEventQueue();
expect(harness.bridge.librarySources, isEmpty);
expect(harness.bridge.connections, contains(record.connectionId));
final session = harness.sessions.single;
session.emit(LinkConnectionState.connected);
session.push({'type': LinkMessageTypes.catalogChanged, 'version': 1});
await Future<void>.delayed(
LinkClientController.rescanDelay + const Duration(milliseconds: 200),
);
expect(
harness.bridge.calls.where((c) => c.startsWith('rescan')),
isEmpty,
);
expect(harness.active, same(session));
harness.container
.read(linkPhoneOptionsProvider.notifier)
.setShowComputerSongs(true);
await pumpEventQueue();
expect(harness.bridge.librarySources[record.connectionId], isTrue);
},
);
test(
'startup hides cached computer songs before starting the session',
() async {
final record = LinkServerRecord(
serverId: 'a',
name: 'Desktop a',
connectionId: 'connection-a',
address: 'https://10.0.0.2:47710',
fingerprint: linkTestFingerprint('a'),
);
SharedPreferences.setMockInitialValues({
LinkClientStore.serversKey: jsonEncode([record.toJson()]),
LinkPhoneOptionsNotifier.showComputerSongsKey: false,
});
final harness = LinkClientHarness();
addTearDown(harness.container.dispose);
harness.bridge.connections[record.connectionId] = const NetworkConnection(
id: 'connection-a',
name: 'Desktop a',
protocol: NetworkProtocol.subsonic,
address: 'https://10.0.0.2:47710',
apiKey: 'saved-key',
subsonicAuth: SubsonicAuth.apiKey,
);
harness.bridge.librarySources[record.connectionId] = true;
await harness.start();
expect(harness.bridge.librarySources[record.connectionId], isFalse);
expect(harness.active, same(harness.sessions.single));
expect(harness.sessions.single.calls, ['start']);
},
);
test('hiding songs waits for an in-flight Library addition', () async {
final harness = await _started();
final entered = Completer<void>();
final release = Completer<void>();
harness.bridge.beforeSourceAdd = () {
entered.complete();
return release.future;
};
final record = await harness.controller.pair(linkTestTarget('a'), '123456');
await entered.future;
harness.container
.read(linkPhoneOptionsProvider.notifier)
.setShowComputerSongs(false);
await pumpEventQueue();
release.complete();
await pumpEventQueue();
expect(harness.bridge.librarySources[record.connectionId], isFalse);
expect(harness.bridge.connections, contains(record.connectionId));
});
test('hiding songs cancels a pending catalog refresh', () async {
final harness = await _started();
await harness.controller.pair(linkTestTarget('a'), '123456');
await pumpEventQueue();
final session = harness.sessions.single;
session.emit(LinkConnectionState.connected);
session.push({'type': LinkMessageTypes.catalogChanged, 'version': 1});
await pumpEventQueue();
harness.container
.read(linkPhoneOptionsProvider.notifier)
.setShowComputerSongs(false);
await Future<void>.delayed(
LinkClientController.rescanDelay + const Duration(milliseconds: 200),
);
expect(harness.bridge.calls.where((c) => c.startsWith('rescan')), isEmpty);
});
test('a failed pairing saves nothing', () async {
final harness = await _started();
harness.pairing.error = LinkPairingError.badPin;
+47
View File
@@ -0,0 +1,47 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mornye/services/link/features/link_phone_options.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('existing users keep computer songs visible by default', () async {
SharedPreferences.setMockInitialValues({});
final container = ProviderContainer();
addTearDown(container.dispose);
await container.read(linkPhoneOptionsProvider.notifier).ensureLoaded();
final options = container.read(linkPhoneOptionsProvider);
expect(options.loaded, isTrue);
expect(options.showComputerSongs, isTrue);
expect(options.shareSongs, isTrue);
});
test(
'computer song visibility persists independently of phone sharing',
() async {
SharedPreferences.setMockInitialValues({});
final container = ProviderContainer();
addTearDown(container.dispose);
final notifier = container.read(linkPhoneOptionsProvider.notifier);
await notifier.ensureLoaded();
notifier.setShowComputerSongs(false);
notifier.setFollowDesktop(false);
await pumpEventQueue();
expect(
(await SharedPreferences.getInstance()).getBool(
LinkPhoneOptionsNotifier.showComputerSongsKey,
),
isFalse,
);
final restored = ProviderContainer();
addTearDown(restored.dispose);
await restored.read(linkPhoneOptionsProvider.notifier).ensureLoaded();
final options = restored.read(linkPhoneOptionsProvider);
expect(options.showComputerSongs, isFalse);
expect(options.shareSongs, isTrue);
expect(options.followDesktop, isFalse);
},
);
}
+16 -1
View File
@@ -339,12 +339,27 @@ void main() {
// What this phone does with the computer shows once paired.
expect(find.text(_l10n.linkPhoneSection), findsOneWidget);
expect(find.text(_l10n.linkShareSongsTitle), findsOneWidget);
final computerSongs = find.text(_l10n.linkShowComputerSongsTitle);
await tester.ensureVisible(computerSongs);
await tester.pump();
await tester.tap(computerSongs);
await _settle(tester);
final prefs = await SharedPreferences.getInstance();
expect(
prefs.getBool(LinkPhoneOptionsNotifier.showComputerSongsKey),
isFalse,
);
expect(harness.bridge.librarySources.values, everyElement(isFalse));
expect(harness.sessions.single.disposed, isFalse);
await tester.tap(computerSongs);
await _settle(tester);
expect(harness.bridge.librarySources.values, everyElement(isTrue));
final follow = find.text(_l10n.linkFollowDesktopTitle);
await tester.ensureVisible(follow);
await tester.pump();
await tester.tap(follow);
await _settle(tester);
final prefs = await SharedPreferences.getInstance();
expect(
prefs.getBool(LinkPhoneOptionsNotifier.followDesktopKey),
isFalse,
+24 -2
View File
@@ -147,6 +147,8 @@ class FakeLinkBrowser implements LinkServiceBrowser {
class FakeLinkBridge implements LinkLibraryBridge {
final connections = <String, NetworkConnection>{};
final calls = <String>[];
final librarySources = <String, bool>{};
Future<void> Function()? beforeSourceAdd;
/// The latest reachability reported for each connection.
final reachable = <String, bool>{};
@@ -170,8 +172,27 @@ class FakeLinkBridge implements LinkLibraryBridge {
calls.add('address $connectionId $address');
@override
Future<void> addLibrarySource(NetworkConnection connection) async =>
calls.add('source ${connection.id}');
Future<void> addLibrarySource(NetworkConnection connection) async {
await beforeSourceAdd?.call();
librarySources[connection.id] = true;
calls.add('source ${connection.id}');
}
@override
Future<void> setLibrarySourceEnabled(
String connectionId,
bool enabled,
) async {
if (enabled) {
final saved = connections[connectionId];
if (saved != null) await addLibrarySource(saved);
} else {
if (librarySources.containsKey(connectionId)) {
librarySources[connectionId] = false;
}
calls.add('hide $connectionId');
}
}
@override
Future<void> rescan(String connectionId) async =>
@@ -180,6 +201,7 @@ class FakeLinkBridge implements LinkLibraryBridge {
@override
Future<void> removeConnection(String connectionId) async {
connections.remove(connectionId);
librarySources.remove(connectionId);
calls.add('remove $connectionId');
}
}