From f1306e825fb2249e246bc33890dcaf7336aaf2be Mon Sep 17 00:00:00 2001 From: zarzet <42882290+zarzet@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:35:13 +0700 Subject: [PATCH] feat(track): copy a track's streaming service link Track menus in both styles and the desktop context menu offer Copy link when the track id names its service: a service prefix or URL, a Spotify id, a source that is itself a service name, or a known Deezer id. Extension ids say nothing about their catalog, so other tracks show no link. Mornye's Share includes the link too. The metadata screen's Open in service button now builds its links from the same helper. Closes mornyeapp/Mornye-Desktop#18. --- lib/l10n/arb/app_en.arb | 10 ++ lib/screens/track_metadata_cards.dart | 35 ++---- lib/screens/track_metadata_screen.dart | 1 + .../track_metadata_screen_display.dart | 56 +-------- lib/utils/service_track_link.dart | 117 ++++++++++++++++++ .../track_collection_quick_actions.dart | 42 ++++++- test/mornye_collection_sheets_test.dart | 95 ++++++++++++++ test/service_track_link_test.dart | 86 +++++++++++++ 8 files changed, 361 insertions(+), 81 deletions(-) create mode 100644 lib/utils/service_track_link.dart create mode 100644 test/service_track_link_test.dart diff --git a/lib/l10n/arb/app_en.arb b/lib/l10n/arb/app_en.arb index b02576724..f6cd0ae44 100644 --- a/lib/l10n/arb/app_en.arb +++ b/lib/l10n/arb/app_en.arb @@ -8124,6 +8124,16 @@ "@trackOptionCopyTrackAndArtist": { "description": "Track menu action that copies the track title and artist" }, + "trackOptionCopyLink": "Copy {service} link", + "@trackOptionCopyLink": { + "description": "Track menu action that copies the track's web link on its streaming service", + "placeholders": { + "service": { + "type": "String", + "description": "Streaming service name, such as Spotify" + } + } + }, "metadataCopyValue": "Copy value", "@metadataCopyValue": { "description": "Metadata menu action that copies only the selected value" diff --git a/lib/screens/track_metadata_cards.dart b/lib/screens/track_metadata_cards.dart index 638a6607d..3652aff03 100644 --- a/lib/screens/track_metadata_cards.dart +++ b/lib/screens/track_metadata_cards.dart @@ -449,33 +449,14 @@ extension _TrackMetadataCards on _TrackMetadataScreenState { _spotifyId!, fallbackService: _service.toLowerCase(), ); - final rawId = _displayServiceTrackId(_spotifyId!); - - String webUrl; - Uri? appUri; - String serviceName; - - if (openService == MusicServices.deezer) { - webUrl = 'https://www.deezer.com/track/$rawId'; - appUri = Uri.parse('deezer://www.deezer.com/track/$rawId'); - serviceName = 'Deezer'; - } else if (openService == MusicServices.amazon) { - webUrl = 'https://music.amazon.com/search/$rawId'; - appUri = Uri.parse('amznm://search/$rawId'); - serviceName = 'Amazon Music'; - } else if (openService == MusicServices.tidal) { - webUrl = 'https://listen.tidal.com/track/$rawId'; - appUri = Uri.parse('tidal://track/$rawId'); - serviceName = 'Tidal'; - } else if (openService == MusicServices.qobuz) { - webUrl = 'https://play.qobuz.com/track/$rawId'; - appUri = Uri.parse('qobuz://track/$rawId'); - serviceName = 'Qobuz'; - } else { - webUrl = 'https://open.spotify.com/track/$rawId'; - appUri = Uri.parse('spotify:track:$rawId'); - serviceName = 'Spotify'; - } + // Unknown services open as Spotify, as this button always has. + final link = ServiceTrackLink( + openService, + _displayServiceTrackId(_spotifyId!), + ); + final webUrl = link.webUrl; + final appUri = link.appUri; + final serviceName = link.serviceName; try { final launched = await launchUrl( diff --git a/lib/screens/track_metadata_screen.dart b/lib/screens/track_metadata_screen.dart index 20c696540..1c33e0b23 100644 --- a/lib/screens/track_metadata_screen.dart +++ b/lib/screens/track_metadata_screen.dart @@ -28,6 +28,7 @@ import 'package:mornye/providers/network_upload_provider.dart'; import 'package:mornye/models/unified_library_item.dart'; import 'package:mornye/utils/file_access.dart'; import 'package:mornye/utils/re_enrich_result.dart'; +import 'package:mornye/utils/service_track_link.dart'; import 'package:path_provider/path_provider.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:share_plus/share_plus.dart'; diff --git a/lib/screens/track_metadata_screen_display.dart b/lib/screens/track_metadata_screen_display.dart index 45408508f..f6271a2a7 100644 --- a/lib/screens/track_metadata_screen_display.dart +++ b/lib/screens/track_metadata_screen_display.dart @@ -1,8 +1,6 @@ // ignore_for_file: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member part of 'track_metadata_screen.dart'; -final _spotifyTrackIdPattern = RegExp(r'^[A-Za-z0-9]{22}$'); - extension _TrackMetadataDisplay on _TrackMetadataScreenState { bool _isBitrateFormatValue(String? value) { return const { @@ -58,58 +56,10 @@ extension _TrackMetadataDisplay on _TrackMetadataScreenState { ); } - String _displayServiceTrackId(String value) { - final raw = value.trim(); - if (raw.isEmpty) return raw; - final spotifyTrackIdPattern = _spotifyTrackIdPattern; + String _displayServiceTrackId(String value) => displayServiceTrackId(value); - if (raw.startsWith('deezer:')) return raw.substring('deezer:'.length); - if (raw.startsWith('tidal:')) return raw.substring('tidal:'.length); - if (raw.startsWith('qobuz:')) return raw.substring('qobuz:'.length); - if (spotifyTrackIdPattern.hasMatch(raw)) return raw; - - if (raw.startsWith('spotify:')) { - final last = raw.split(':').last.trim(); - if (spotifyTrackIdPattern.hasMatch(last)) return last; - return raw; - } - - final uri = Uri.tryParse(raw); - if (uri != null && - uri.host.contains('spotify.com') && - uri.pathSegments.length >= 2 && - uri.pathSegments.first == 'track') { - final candidate = uri.pathSegments[1].trim(); - if (spotifyTrackIdPattern.hasMatch(candidate)) { - return candidate; - } - } - - return raw; - } - - String _serviceForTrackId(String value, {required String fallbackService}) { - final raw = value.trim(); - if (raw.isEmpty) return fallbackService; - final spotifyTrackIdPattern = _spotifyTrackIdPattern; - - if (raw.startsWith('deezer:')) return MusicServices.deezer; - if (raw.startsWith('tidal:')) return MusicServices.tidal; - if (raw.startsWith('qobuz:')) return MusicServices.qobuz; - if (raw.startsWith('spotify:')) return MusicServices.spotify; - if (spotifyTrackIdPattern.hasMatch(raw)) return MusicServices.spotify; - - final uri = Uri.tryParse(raw); - if (uri != null) { - final host = uri.host.toLowerCase(); - if (host.contains('spotify.com')) return MusicServices.spotify; - if (host.contains('deezer.com')) return MusicServices.deezer; - if (host.contains('tidal.com')) return MusicServices.tidal; - if (host.contains('qobuz.com')) return MusicServices.qobuz; - } - - return fallbackService; - } + String _serviceForTrackId(String value, {required String fallbackService}) => + serviceForTrackId(value, fallbackService: fallbackService); String? get _displayAudioQuality { final fileName = _extractFileNameFromPathOrUri(cleanFilePath); diff --git a/lib/utils/service_track_link.dart b/lib/utils/service_track_link.dart new file mode 100644 index 000000000..4a1d5540d --- /dev/null +++ b/lib/utils/service_track_link.dart @@ -0,0 +1,117 @@ +import 'package:mornye/constants/music_services.dart'; +import 'package:mornye/models/track.dart'; + +final _spotifyTrackIdPattern = RegExp(r'^[A-Za-z0-9]{22}$'); + +/// A track's page on the streaming service its id came from. +class ServiceTrackLink { + const ServiceTrackLink(this.service, this.id); + + /// One of the [MusicServices] streaming services. + final String service; + + /// The service's own track id, without a `service:` prefix. + final String id; + + String get serviceName => switch (service) { + MusicServices.deezer => 'Deezer', + MusicServices.amazon => 'Amazon Music', + MusicServices.tidal => 'Tidal', + MusicServices.qobuz => 'Qobuz', + _ => 'Spotify', + }; + + String get webUrl => switch (service) { + MusicServices.deezer => 'https://www.deezer.com/track/$id', + MusicServices.amazon => 'https://music.amazon.com/search/$id', + MusicServices.tidal => 'https://listen.tidal.com/track/$id', + MusicServices.qobuz => 'https://play.qobuz.com/track/$id', + _ => 'https://open.spotify.com/track/$id', + }; + + /// The service app's own link, tried before [webUrl]. + Uri get appUri => switch (service) { + MusicServices.deezer => Uri.parse('deezer://www.deezer.com/track/$id'), + MusicServices.amazon => Uri.parse('amznm://search/$id'), + MusicServices.tidal => Uri.parse('tidal://track/$id'), + MusicServices.qobuz => Uri.parse('qobuz://track/$id'), + _ => Uri.parse('spotify:track:$id'), + }; +} + +const _streamingServices = { + MusicServices.spotify, + MusicServices.deezer, + MusicServices.tidal, + MusicServices.qobuz, + MusicServices.amazon, +}; + +/// The service [value] names through a prefix, a service URL or a Spotify +/// id, or [fallbackService] when it names none. +String serviceForTrackId(String value, {required String fallbackService}) { + final raw = value.trim(); + if (raw.isEmpty) return fallbackService; + if (raw.startsWith('deezer:')) return MusicServices.deezer; + if (raw.startsWith('tidal:')) return MusicServices.tidal; + if (raw.startsWith('qobuz:')) return MusicServices.qobuz; + if (raw.startsWith('spotify:')) return MusicServices.spotify; + if (_spotifyTrackIdPattern.hasMatch(raw)) return MusicServices.spotify; + + final uri = Uri.tryParse(raw); + if (uri != null) { + final host = uri.host.toLowerCase(); + if (host.contains('spotify.com')) return MusicServices.spotify; + if (host.contains('deezer.com')) return MusicServices.deezer; + if (host.contains('tidal.com')) return MusicServices.tidal; + if (host.contains('qobuz.com')) return MusicServices.qobuz; + } + return fallbackService; +} + +/// [value] without its `service:` prefix or Spotify URL wrapping. +String displayServiceTrackId(String value) { + final raw = value.trim(); + if (raw.isEmpty) return raw; + + if (raw.startsWith('deezer:')) return raw.substring('deezer:'.length); + if (raw.startsWith('tidal:')) return raw.substring('tidal:'.length); + if (raw.startsWith('qobuz:')) return raw.substring('qobuz:'.length); + if (_spotifyTrackIdPattern.hasMatch(raw)) return raw; + + if (raw.startsWith('spotify:')) { + final last = raw.split(':').last.trim(); + if (_spotifyTrackIdPattern.hasMatch(last)) return last; + return raw; + } + + final uri = Uri.tryParse(raw); + if (uri != null && + uri.host.contains('spotify.com') && + uri.pathSegments.length >= 2 && + uri.pathSegments.first == 'track') { + final candidate = uri.pathSegments[1].trim(); + if (_spotifyTrackIdPattern.hasMatch(candidate)) return candidate; + } + return raw; +} + +/// The service page of [track], or null when its id does not say which +/// streaming service it belongs to. A source counts only when it is itself a +/// service name, since extension ids say nothing about their catalog. +ServiceTrackLink? serviceTrackLinkFor(Track track) { + final source = track.source?.trim().toLowerCase() ?? ''; + final fallback = _streamingServices.contains(source) ? source : ''; + final service = serviceForTrackId(track.id, fallbackService: fallback); + if (service.isNotEmpty) { + final id = displayServiceTrackId(track.id); + if (id.isNotEmpty && !id.contains('/') && !id.contains(':')) { + return ServiceTrackLink(service, id); + } + } + final deezerId = track.deezerId?.trim() ?? ''; + if (RegExp(r'^\d+$').hasMatch(deezerId)) { + return ServiceTrackLink(MusicServices.deezer, deezerId); + } + return null; +} diff --git a/lib/widgets/track_collection_quick_actions.dart b/lib/widgets/track_collection_quick_actions.dart index 6cabf38e1..1719f5b21 100644 --- a/lib/widgets/track_collection_quick_actions.dart +++ b/lib/widgets/track_collection_quick_actions.dart @@ -13,6 +13,7 @@ import 'package:mornye/services/cover_cache_manager.dart'; import 'package:mornye/controllers/clickable_metadata.dart'; import 'package:mornye/controllers/local_playback.dart'; import 'package:mornye/utils/desktop_platform.dart'; +import 'package:mornye/utils/service_track_link.dart'; import 'package:mornye/widgets/desktop/context_menu.dart'; import 'package:mornye/widgets/link/link_actions.dart'; import 'package:mornye/widgets/playlist_picker_sheet.dart'; @@ -133,6 +134,7 @@ List> trackOptionMenuGroups( allowQualityVariants: ref.read(settingsProvider).allowQualityVariants, hasLocalPlaybackCandidate: hasLocalPlaybackCandidate, ); + final link = serviceTrackLinkFor(track); void notify(String message) { if (!root.mounted) return; @@ -235,6 +237,17 @@ List> trackOptionMenuGroups( label: l10n.trackOptionCopyTrackAndArtist, onSelected: () => copy('${track.name} - ${track.artistName}'), ), + if (link != null) + ContextMenuAction( + icon: Icons.link, + label: l10n.trackOptionCopyLink(link.serviceName), + onSelected: () { + Clipboard.setData(ClipboardData(text: link.webUrl)); + if (root.mounted) { + notify(root.l10n.snackbarUrlCopied(link.serviceName)); + } + }, + ), ], ]; } @@ -251,6 +264,7 @@ class _TrackOptionsSheet extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final colorScheme = Theme.of(context).colorScheme; + final link = serviceTrackLinkFor(track); final isLoved = ref.watch( libraryCollectionsProvider.select((state) => state.isLoved(track)), @@ -300,7 +314,10 @@ class _TrackOptionsSheet extends ConsumerWidget { Navigator.pop(context); SharePlus.instance.share( ShareParams( - text: '${track.name} — ${track.artistName}', + text: [ + '${track.name} - ${track.artistName}', + ?link?.webUrl, + ].join('\n'), sharePositionOrigin: origin, ), ); @@ -371,6 +388,12 @@ class _TrackOptionsSheet extends ConsumerWidget { onPressed: () => _copyText(context, '${track.name} - ${track.artistName}'), ), + if (link != null) + MornyeMenuAction( + icon: CupertinoIcons.link, + label: l10n.trackOptionCopyLink(link.serviceName), + onPressed: () => _copyLink(context, link), + ), ], ], ); @@ -502,6 +525,12 @@ class _TrackOptionsSheet extends ConsumerWidget { onTap: () => _copyText(context, '${track.name} - ${track.artistName}'), ), + if (link != null) + _OptionTile( + icon: Icons.link, + title: context.l10n.trackOptionCopyLink(link.serviceName), + onTap: () => _copyLink(context, link), + ), _OptionTile( icon: Icons.album_outlined, @@ -626,6 +655,17 @@ class _TrackOptionsSheet extends ConsumerWidget { ); } + void _copyLink(BuildContext context, ServiceTrackLink link) { + final rootContext = Navigator.of(context, rootNavigator: true).context; + Navigator.pop(context); + Clipboard.setData(ClipboardData(text: link.webUrl)); + ScaffoldMessenger.of(rootContext).showSnackBar( + SnackBar( + content: Text(rootContext.l10n.snackbarUrlCopied(link.serviceName)), + ), + ); + } + Future _goToAlbum(BuildContext context) async { final navigationContext = Navigator.of( context, diff --git a/test/mornye_collection_sheets_test.dart b/test/mornye_collection_sheets_test.dart index 3d9d2db46..c6e403245 100644 --- a/test/mornye_collection_sheets_test.dart +++ b/test/mornye_collection_sheets_test.dart @@ -129,6 +129,101 @@ void main() { .load(); }); + for (final mornye in [true, false]) { + testWidgets('track menu copies the service link (Mornye: $mornye)', ( + tester, + ) async { + String? copied; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + copied = (call.arguments as Map)['text'] as String?; + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + const linked = Track( + id: 'example-track', + name: 'Example track', + artistName: 'Example artist', + albumName: 'Example album', + duration: 180, + deezerId: '42', + ); + await tester.pumpWidget( + _app( + const TrackCollectionQuickActions(track: linked), + _Collections(), + brightness: Brightness.light, + mornye: mornye, + ), + ); + await tester.tap(find.byType(TrackCollectionQuickActions)); + await tester.pumpAndSettle(); + final action = find.text('Copy Deezer link'); + await tester.ensureVisible(action); + await tester.tap(action); + await tester.pumpAndSettle(); + expect(copied, 'https://www.deezer.com/track/42'); + expect(find.text('Deezer URL copied to clipboard'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + } + + testWidgets('desktop track menu offers the link only when known', ( + tester, + ) async { + final labels = >{}; + const linked = Track( + id: 'deezer:42', + name: 'Example track', + artistName: 'Example artist', + albumName: 'Example album', + duration: 180, + ); + await tester.pumpWidget( + _app( + Consumer( + builder: (context, ref, _) { + for (final track in [_track, linked]) { + labels[track.id] = [ + for (final group in trackOptionMenuGroups(context, ref, track)) + for (final action in group) action.label, + ]; + } + return const SizedBox(); + }, + ), + _Collections(), + brightness: Brightness.light, + ), + ); + expect(labels['deezer:42'], contains('Copy Deezer link')); + expect(labels['example-track']!.where((l) => l.contains('link')), isEmpty); + }); + + testWidgets('track menu hides the link for an unknown service', ( + tester, + ) async { + await tester.pumpWidget( + _app( + const TrackCollectionQuickActions(track: _track), + _Collections(), + brightness: Brightness.light, + ), + ); + await tester.tap(find.byIcon(CupertinoIcons.ellipsis)); + await tester.pumpAndSettle(); + expect(find.textContaining('link'), findsNothing); + }); + for (final brightness in Brightness.values) { testWidgets('track menu reaches playlist creation in $brightness', ( tester, diff --git a/test/service_track_link_test.dart b/test/service_track_link_test.dart new file mode 100644 index 000000000..cbcc704fe --- /dev/null +++ b/test/service_track_link_test.dart @@ -0,0 +1,86 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mornye/models/track.dart'; +import 'package:mornye/utils/service_track_link.dart'; + +// Service names here are the app's fixed link formats, not extension ids. +Track _track(String id, {String? source, String? deezerId}) => Track( + id: id, + name: 'Example track', + artistName: 'Example artist', + albumName: 'Example album', + duration: 180, + source: source, + deezerId: deezerId, +); + +void main() { + test('a prefixed id links to its own service', () { + expect( + serviceTrackLinkFor(_track('deezer:3135556'))?.webUrl, + 'https://www.deezer.com/track/3135556', + ); + expect( + serviceTrackLinkFor(_track('tidal:77640617'))?.webUrl, + 'https://listen.tidal.com/track/77640617', + ); + expect( + serviceTrackLinkFor(_track('qobuz:12345678'))?.webUrl, + 'https://play.qobuz.com/track/12345678', + ); + final spotify = serviceTrackLinkFor( + _track('spotify:track:4uLU6hMCjMI75M1A2tKUQC'), + ); + expect(spotify?.serviceName, 'Spotify'); + expect( + spotify?.webUrl, + 'https://open.spotify.com/track/4uLU6hMCjMI75M1A2tKUQC', + ); + }); + + test('a bare id needs a source that names the service', () { + expect( + serviceTrackLinkFor(_track('3135556', source: 'deezer'))?.webUrl, + 'https://www.deezer.com/track/3135556', + ); + expect(serviceTrackLinkFor(_track('3135556')), isNull); + expect( + serviceTrackLinkFor(_track('3135556', source: 'example-extension')), + isNull, + ); + }); + + test('a known Deezer id is the fallback for unknown ids', () { + final link = serviceTrackLinkFor( + _track('example-track', source: 'example-extension', deezerId: '42'), + ); + expect(link?.webUrl, 'https://www.deezer.com/track/42'); + expect(link?.serviceName, 'Deezer'); + }); + + test('local and malformed ids have no link', () { + expect(serviceTrackLinkFor(_track('/music/song.flac')), isNull); + expect(serviceTrackLinkFor(_track('content://media/12')), isNull); + expect(serviceTrackLinkFor(_track('')), isNull); + expect( + serviceTrackLinkFor(_track('example-track', deezerId: 'abc')), + isNull, + ); + }); + + test('service URLs keep the id the metadata screen showed', () { + expect( + displayServiceTrackId( + 'https://open.spotify.com/track/4uLU6hMCjMI75M1A2tKUQC', + ), + '4uLU6hMCjMI75M1A2tKUQC', + ); + expect( + serviceForTrackId( + 'https://listen.tidal.com/track/1', + fallbackService: '', + ), + 'tidal', + ); + expect(serviceForTrackId('abc', fallbackService: 'local'), 'local'); + }); +}