From b889dabbb41539fdd8a97c624257570a1490e407 Mon Sep 17 00:00:00 2001 From: zarzet <42882290+zarzet@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:27:48 +0700 Subject: [PATCH] feat(link): add computer library visibility toggle --- lib/l10n/arb/app_en.arb | 17 +++ lib/screens/settings/link_settings_page.dart | 15 +- .../link/client/link_client_controller.dart | 58 ++++++-- .../link/client/link_client_library.dart | 23 +++ .../link/features/link_phone_options.dart | 32 +++- test/link_client_controller_test.dart | 137 ++++++++++++++++++ test/link_phone_options_test.dart | 47 ++++++ test/link_settings_page_test.dart | 17 ++- test/support/link_client_fakes.dart | 26 +++- 9 files changed, 352 insertions(+), 20 deletions(-) create mode 100644 test/link_phone_options_test.dart diff --git a/lib/l10n/arb/app_en.arb b/lib/l10n/arb/app_en.arb index 3baead1c2..093df4bec 100644 --- a/lib/l10n/arb/app_en.arb +++ b/lib/l10n/arb/app_en.arb @@ -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" diff --git a/lib/screens/settings/link_settings_page.dart b/lib/screens/settings/link_settings_page.dart index 26d6a5278..b4644cb7b 100644 --- a/lib/screens/settings/link_settings_page.dart +++ b/lib/screens/settings/link_settings_page.dart @@ -127,7 +127,11 @@ class _LinkSettingsPageState extends ConsumerState { ), ); 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 { ...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, diff --git a/lib/services/link/client/link_client_controller.dart b/lib/services/link/client/link_client_controller.dart index 3d2f23bed..48f2d31a4 100644 --- a/lib/services/link/client/link_client_controller.dart +++ b/lib/services/link/client/link_client_controller.dart @@ -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 { 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 ensureLoaded() => _loading ?? Future.value(); @@ -287,6 +290,20 @@ class LinkClientController extends Notifier { (_, 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.microtask( () => _serial(_load).catchError( @@ -304,6 +321,8 @@ class LinkClientController extends Notifier { } Future _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 { activeServerId: active, clearActiveServer: active == null, ); - await _restartSession(); + if (!_showComputerSongs) await _syncLibrarySources(); + if (!_disposed) await _restartSession(); + } + + Future _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 _identity() async { @@ -427,9 +460,11 @@ class LinkClientController extends Notifier { 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 { }); /// 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 pair(LinkPairingTarget target, String pin) async { final result = await ref .read(linkPairingApiProvider) @@ -813,12 +848,17 @@ class LinkClientController extends Notifier { 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; } diff --git a/lib/services/link/client/link_client_library.dart b/lib/services/link/client/link_client_library.dart index cf51b1873..9376da9ec 100644 --- a/lib/services/link/client/link_client_library.dart +++ b/lib/services/link/client/link_client_library.dart @@ -27,6 +27,9 @@ abstract interface class LinkLibraryBridge { /// storage screen does after adding a Subsonic server. Future addLibrarySource(NetworkConnection connection); + /// Shows or hides the indexed songs, keeping the network connection. + Future setLibrarySourceEnabled(String connectionId, bool enabled); + /// Rescans the connection's Library source incrementally, after any /// running scan. Future rescan(String connectionId); @@ -107,6 +110,26 @@ class LinkNetworkLibraryBridge implements LinkLibraryBridge { _scan(source.id); } + @override + Future 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 rescan(String connectionId) async { final source = await _database.getSourceByPath(_rootSource(connectionId)); diff --git a/lib/services/link/features/link_phone_options.dart b/lib/services/link/features/link_phone_options.dart index ae558f8e8..257d9792f 100644 --- a/lib/services/link/features/link_phone_options.dart +++ b/lib/services/link/features/link_phone_options.dart @@ -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 { 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? _loading; + + Future 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 { 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 { 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))); diff --git a/test/link_client_controller_test.dart b/test/link_client_controller_test.dart index 928f23acc..e65602cd4 100644 --- a/test/link_client_controller_test.dart +++ b/test/link_client_controller_test.dart @@ -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.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(); + final release = Completer(); + 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.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; diff --git a/test/link_phone_options_test.dart b/test/link_phone_options_test.dart new file mode 100644 index 000000000..a527237c7 --- /dev/null +++ b/test/link_phone_options_test.dart @@ -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); + }, + ); +} diff --git a/test/link_settings_page_test.dart b/test/link_settings_page_test.dart index b8f1e9fa9..732b9233c 100644 --- a/test/link_settings_page_test.dart +++ b/test/link_settings_page_test.dart @@ -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, diff --git a/test/support/link_client_fakes.dart b/test/support/link_client_fakes.dart index f30d54852..55af1eeab 100644 --- a/test/support/link_client_fakes.dart +++ b/test/support/link_client_fakes.dart @@ -147,6 +147,8 @@ class FakeLinkBrowser implements LinkServiceBrowser { class FakeLinkBridge implements LinkLibraryBridge { final connections = {}; final calls = []; + final librarySources = {}; + Future Function()? beforeSourceAdd; /// The latest reachability reported for each connection. final reachable = {}; @@ -170,8 +172,27 @@ class FakeLinkBridge implements LinkLibraryBridge { calls.add('address $connectionId $address'); @override - Future addLibrarySource(NetworkConnection connection) async => - calls.add('source ${connection.id}'); + Future addLibrarySource(NetworkConnection connection) async { + await beforeSourceAdd?.call(); + librarySources[connection.id] = true; + calls.add('source ${connection.id}'); + } + + @override + Future 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 rescan(String connectionId) async => @@ -180,6 +201,7 @@ class FakeLinkBridge implements LinkLibraryBridge { @override Future removeConnection(String connectionId) async { connections.remove(connectionId); + librarySources.remove(connectionId); calls.add('remove $connectionId'); } }