diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index d038beb70..f69b8f75e 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -10,6 +10,10 @@ on: - "lib/widgets/duplicate_review_sheet.dart" - "test/duplicate_review_sheet_test.dart" - "test/settings_bottom_inset_test.dart" + - "lib/services/lastfm/**" + - "lib/widgets/lastfm_settings.dart" + - "test/lastfm*_test.dart" + - "test/support/lastfm_fakes.dart" - "rust_backend/**" - "third_party/**" - "scripts/build_rust_backend.sh" @@ -101,6 +105,7 @@ jobs: run: | dart scripts/prepare_flutter_sdk.dart flutter test --no-pub test/semantics_geometry_regression_test.dart + flutter test --no-pub test/lastfm_api_test.dart test/lastfm_listening_test.dart test/lastfm_service_test.dart test/lastfm_store_test.dart test/lastfm_settings_test.dart # The Xcode "Embed Rust Backend" and "Embed FFmpeg" phases embed the # library and the FFmpeg tools built above. @@ -108,8 +113,12 @@ jobs: env: MORNYE_SKIP_RUST_BUILD: "1" MORNYE_REQUIRE_FFMPEG: "1" + LASTFM_API_KEY: ${{ secrets.LASTFM_API_KEY }} + LASTFM_API_SECRET: ${{ secrets.LASTFM_API_SECRET }} run: | flutter build macos --release --target lib/main.dart \ + --dart-define="LASTFM_API_KEY=$LASTFM_API_KEY" \ + --dart-define="LASTFM_API_SECRET=$LASTFM_API_SECRET" \ --dart-define="GIT_COMMIT=$(git rev-parse --short=8 HEAD)" - name: Verify and package macOS app @@ -244,8 +253,13 @@ jobs: run: flutter test --reporter expanded test/duplicate_review_sheet_test.dart test/desktop_updater_test.dart test/settings_bottom_inset_test.dart test/semantics_geometry_regression_test.dart - name: Build Linux bundle + env: + LASTFM_API_KEY: ${{ secrets.LASTFM_API_KEY }} + LASTFM_API_SECRET: ${{ secrets.LASTFM_API_SECRET }} run: | flutter build linux --release --target lib/main.dart \ + --dart-define="LASTFM_API_KEY=$LASTFM_API_KEY" \ + --dart-define="LASTFM_API_SECRET=$LASTFM_API_SECRET" \ --dart-define="GIT_COMMIT=$(git rev-parse --short=8 HEAD)" - name: Verify and package Linux bundle @@ -361,9 +375,12 @@ jobs: run: flutter test --reporter expanded test/duplicate_review_sheet_test.dart test/desktop_updater_test.dart test/settings_bottom_inset_test.dart test/semantics_geometry_regression_test.dart - name: Build Windows app + env: + LASTFM_API_KEY: ${{ secrets.LASTFM_API_KEY }} + LASTFM_API_SECRET: ${{ secrets.LASTFM_API_SECRET }} run: | $commit = git rev-parse --short=8 HEAD - flutter build windows --release --target lib/main.dart --dart-define="GIT_COMMIT=$commit" + flutter build windows --release --target lib/main.dart --dart-define="GIT_COMMIT=$commit" --dart-define="LASTFM_API_KEY=$env:LASTFM_API_KEY" --dart-define="LASTFM_API_SECRET=$env:LASTFM_API_SECRET" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Verify and package Windows app diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bac33707e..4864d4b8f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -466,8 +466,12 @@ jobs: env: MORNYE_SKIP_RUST_BUILD: "1" MORNYE_REQUIRE_FFMPEG: "1" + LASTFM_API_KEY: ${{ secrets.LASTFM_API_KEY }} + LASTFM_API_SECRET: ${{ secrets.LASTFM_API_SECRET }} run: | flutter build macos --release --target lib/main.dart \ + --dart-define="LASTFM_API_KEY=$LASTFM_API_KEY" \ + --dart-define="LASTFM_API_SECRET=$LASTFM_API_SECRET" \ --dart-define="GIT_COMMIT=$(git rev-parse --short=8 HEAD)" - name: Package disk image @@ -583,8 +587,13 @@ jobs: # linux/CMakeLists.txt installs the Rust library into lib/ and the # FFmpeg tools staged above into lib/ffmpeg/. - name: Build Linux bundle + env: + LASTFM_API_KEY: ${{ secrets.LASTFM_API_KEY }} + LASTFM_API_SECRET: ${{ secrets.LASTFM_API_SECRET }} run: | flutter build linux --release --target lib/main.dart \ + --dart-define="LASTFM_API_KEY=$LASTFM_API_KEY" \ + --dart-define="LASTFM_API_SECRET=$LASTFM_API_SECRET" \ --dart-define="GIT_COMMIT=$(git rev-parse --short=8 HEAD)" - name: Validate desktop entry and AppStream metadata @@ -729,9 +738,12 @@ jobs: # windows/CMakeLists.txt installs the Rust library next to mornye.exe # and the FFmpeg tools staged above into ffmpeg\. - name: Build Windows app + env: + LASTFM_API_KEY: ${{ secrets.LASTFM_API_KEY }} + LASTFM_API_SECRET: ${{ secrets.LASTFM_API_SECRET }} run: | $commit = git rev-parse --short=8 HEAD - flutter build windows --release --target lib/main.dart --dart-define="GIT_COMMIT=$commit" + flutter build windows --release --target lib/main.dart --dart-define="GIT_COMMIT=$commit" --dart-define="LASTFM_API_KEY=$env:LASTFM_API_KEY" --dart-define="LASTFM_API_SECRET=$env:LASTFM_API_SECRET" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $bundle = 'build\windows\${{ matrix.arch }}\runner\Release' ./scripts/check_windows_bundle.ps1 -BundleDir $bundle -Arch ${{ matrix.arch }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9d6ebf34a..7276cae57 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -137,6 +137,28 @@ SHA-256 hashes, Dart symbols, and R8 mapping, identified by run and attempt. Archive it before its 90-day retention expires and match the reported APK hash when choosing symbols; equal version numbers do not guarantee a match. +### Last.fm Desktop Integration + +Create a Last.fm API account for Mornye at +. Desktop authorization uses a request +token and a browser approval, so no callback URL is needed. Put its API key +and shared secret in the Git-ignored `.env.lastfm` file: + +```dotenv +LASTFM_API_KEY=your_application_key +LASTFM_API_SECRET=your_application_shared_secret +``` + +Pass `--dart-define-from-file=.env.lastfm` to `fvm flutter run` or a desktop +Flutter build. Desktop CI and release jobs read the repository secrets +`LASTFM_API_KEY` and `LASTFM_API_SECRET`; fork builds omit the integration's +credentials. Never commit real values. Each listener's session is stored +separately in the OS secure storage and is not part of the offline queue. + +The controls are in Settings > Playback > Last.fm. Only the local built-in +player is observed, including music a paired device asks it to play. A Link +remote session and catalog previews do not submit listening history. + ## Project Boundaries ```text diff --git a/lib/l10n/arb/app_en.arb b/lib/l10n/arb/app_en.arb index 57fe01926..12e74522d 100644 --- a/lib/l10n/arb/app_en.arb +++ b/lib/l10n/arb/app_en.arb @@ -10061,6 +10061,30 @@ "@collectionSuggestionsRefresh": { "description": "Tooltip of the button that loads other suggestions" }, + "lastfmDescription": "Track your listening and show what is playing on Last.fm.", + "lastfmConnect": "Connect Last.fm", + "lastfmConnecting": "Connecting to Last.fm...", + "lastfmFinishConnection": "Finish connecting", + "lastfmAuthorizeHelp": "Approve access in your browser, then return here and choose Finish connecting.", + "lastfmScrobbling": "Scrobbling", + "lastfmScrobblingDescription": "Send songs you listen to in the built-in player to Last.fm.", + "lastfmNowPlaying": "Show Now Playing", + "lastfmNowPlayingDescription": "Show the current song on your Last.fm profile.", + "lastfmDisconnect": "Disconnect Last.fm", + "lastfmConnectionError": "Last.fm could not be reached. Saved scrobbles will be retried automatically.", + "lastfmStorageError": "Last.fm settings could not be saved. Check access to this device's secure storage and try again.", + "lastfmAuthorizationPending": "Access has not been approved yet. Finish authorizing Mornye in your browser.", + "lastfmAuthorizationExpired": "This connection request expired. Connect again to continue.", + "lastfmReauthenticate": "Your Last.fm connection expired. Connect again to resume scrobbling.", + "lastfmUnavailable": "Last.fm is unavailable in this build.", + "lastfmRejected": "Last.fm rejected a scrobble. Check the song's title and artist tags.", + "lastfmPending": "{count, plural, =1{1 scrobble waiting to sync} other{{count} scrobbles waiting to sync}}", + "@lastfmPending": { + "description": "Number of saved Last.fm scrobbles awaiting submission", + "placeholders": { + "count": { "type": "int" } + } + }, "collectionSuggestionsAddHere": "Add to this playlist", "@collectionSuggestionsAddHere": { "description": "Tooltip of the button that adds a suggested song to the user's playlist shown above" diff --git a/lib/l10n/arb/app_id.arb b/lib/l10n/arb/app_id.arb index b2973776a..c11042bdc 100644 --- a/lib/l10n/arb/app_id.arb +++ b/lib/l10n/arb/app_id.arb @@ -8388,5 +8388,23 @@ "playlistCreatedWithTracks": "{name} dibuat dengan {count, plural, =1{1 lagu} other{{count} lagu}}", "playlistImportResult": "{count, plural, =1{1 lagu} other{{count} lagu}} diimpor ke {name}, {matched} cocok dengan file di perangkat ini", "playlistImportNoTracks": "Tidak ada lagu di file ini", - "playlistImportFailed": "File playlist ini tidak dapat dibaca" + "playlistImportFailed": "File playlist ini tidak dapat dibaca", + "lastfmDescription": "Catat aktivitas mendengarkan dan tampilkan lagu yang diputar di Last.fm.", + "lastfmConnect": "Hubungkan Last.fm", + "lastfmConnecting": "Menghubungkan ke Last.fm...", + "lastfmFinishConnection": "Selesaikan koneksi", + "lastfmAuthorizeHelp": "Izinkan akses di browser, lalu kembali ke sini dan pilih Selesaikan koneksi.", + "lastfmScrobbling": "Scrobbling", + "lastfmScrobblingDescription": "Kirim lagu yang Anda dengarkan lewat pemutar bawaan ke Last.fm.", + "lastfmNowPlaying": "Tampilkan lagu yang diputar", + "lastfmNowPlayingDescription": "Tampilkan lagu saat ini di profil Last.fm Anda.", + "lastfmDisconnect": "Putuskan Last.fm", + "lastfmConnectionError": "Last.fm tidak dapat dihubungi. Scrobble yang tersimpan akan dikirim ulang secara otomatis.", + "lastfmStorageError": "Pengaturan Last.fm tidak dapat disimpan. Periksa akses penyimpanan aman perangkat ini lalu coba lagi.", + "lastfmAuthorizationPending": "Akses belum disetujui. Selesaikan izin Mornye di browser.", + "lastfmAuthorizationExpired": "Permintaan koneksi ini kedaluwarsa. Hubungkan kembali untuk melanjutkan.", + "lastfmReauthenticate": "Koneksi Last.fm Anda kedaluwarsa. Hubungkan kembali untuk melanjutkan scrobbling.", + "lastfmUnavailable": "Last.fm tidak tersedia pada build ini.", + "lastfmRejected": "Last.fm menolak scrobble. Periksa tag judul dan artis lagu tersebut.", + "lastfmPending": "{count, plural, =1{1 scrobble menunggu sinkronisasi} other{{count} scrobble menunggu sinkronisasi}}" } diff --git a/lib/screens/settings/playback_settings_page.dart b/lib/screens/settings/playback_settings_page.dart index c7f0958d8..8f13856bc 100644 --- a/lib/screens/settings/playback_settings_page.dart +++ b/lib/screens/settings/playback_settings_page.dart @@ -32,6 +32,7 @@ import 'package:mornye/widgets/beta_badge.dart'; import 'package:mornye/widgets/player_volume_control.dart'; import 'package:mornye/widgets/settings_group.dart'; import 'package:mornye/widgets/discord_presence_settings.dart'; +import 'package:mornye/widgets/lastfm_settings.dart'; import 'package:mornye/widgets/automix_settings.dart'; import 'package:mornye/widgets/music_haptics_settings.dart'; import 'package:mornye/widgets/playback_normalization_settings.dart'; @@ -448,6 +449,16 @@ class _PlaybackSettingsPageState extends ConsumerState ), const SliverToBoxAdapter(child: DiscordPresenceSettings()), ], + if (isDesktopPlatform) ...[ + const SliverToBoxAdapter( + child: SettingsSectionHeader(title: 'Last.fm'), + ), + SliverToBoxAdapter( + child: LastfmSettings( + service: ref.read(musicPlayerRuntimeProvider).lastfm, + ), + ), + ], if (isDesktopPlatform) ...settingsSectionSlivers( title: context.l10n.sectionAudioOutput, diff --git a/lib/services/lastfm/lastfm_api.dart b/lib/services/lastfm/lastfm_api.dart new file mode 100644 index 000000000..bde32006a --- /dev/null +++ b/lib/services/lastfm/lastfm_api.dart @@ -0,0 +1,153 @@ +import 'dart:convert'; + +import 'package:crypto/crypto.dart'; +import 'package:http/http.dart' as http; + +class LastfmCredentials { + const LastfmCredentials({ + this.apiKey = const String.fromEnvironment('LASTFM_API_KEY'), + this.apiSecret = const String.fromEnvironment('LASTFM_API_SECRET'), + }); + + final String apiKey; + final String apiSecret; + + bool get configured => apiKey.isNotEmpty && apiSecret.isNotEmpty; +} + +class LastfmSession { + const LastfmSession({required this.username, required this.key}); + + factory LastfmSession.fromJson(Map json) { + final username = json['name'] as String? ?? ''; + final key = json['key'] as String? ?? ''; + if (username.isEmpty || key.isEmpty) { + throw const FormatException('Invalid Last.fm session'); + } + return LastfmSession(username: username, key: key); + } + + final String username; + final String key; + + Map toJson() => {'name': username, 'key': key}; +} + +class LastfmException implements Exception { + const LastfmException(this.code); + + final int code; + + bool get retryable => const {11, 16, 29}.contains(code); + + @override + String toString() => 'Last.fm request failed (code $code)'; +} + +/// Last.fm signs the original UTF-8 parameter values, before form encoding. +/// Response format and callback parameters are excluded from the signature. +String lastfmSignature(Map parameters, String secret) { + final keys = + parameters.keys + .where( + (key) => !const {'format', 'callback', 'api_sig'}.contains(key), + ) + .toList() + ..sort(); + final input = '${keys.map((key) => '$key${parameters[key]}').join()}$secret'; + return md5.convert(utf8.encode(input)).toString(); +} + +class LastfmApi { + LastfmApi({this.credentials = const LastfmCredentials(), http.Client? client}) + : _client = client ?? http.Client(); + + final LastfmCredentials credentials; + final http.Client _client; + static final _endpoint = Uri.https('ws.audioscrobbler.com', '/2.0/'); + + Future> _request( + String method, + Map parameters, + ) async { + if (!credentials.configured) throw const LastfmException(10); + final body = { + ...parameters, + 'method': method, + 'api_key': credentials.apiKey, + }; + body['api_sig'] = lastfmSignature(body, credentials.apiSecret); + body['format'] = 'json'; + final response = await _client + .post(_endpoint, body: body) + .timeout(const Duration(seconds: 15)); + if (response.statusCode == 429) throw const LastfmException(29); + if (response.statusCode >= 500) throw const LastfmException(16); + // HTTP 200 can still contain an API error. Never include the response + // body or request parameters in exceptions, as they can contain tokens. + final decoded = jsonDecode(response.body); + if (decoded is! Map) { + throw const FormatException('Invalid Last.fm response'); + } + final code = decoded['error']; + if (code is num) throw LastfmException(code.toInt()); + if (response.statusCode != 200) { + throw const FormatException('Unexpected Last.fm HTTP response'); + } + return decoded; + } + + Future requestToken() async { + final response = await _request('auth.getToken', const {}); + final token = response['token'] as String? ?? ''; + if (token.isEmpty) throw const FormatException('Missing Last.fm token'); + return token; + } + + Uri authorizationUrl(String token) => Uri.https('www.last.fm', '/api/auth/', { + 'api_key': credentials.apiKey, + 'token': token, + }); + + Future session(String token) async { + final response = await _request('auth.getSession', {'token': token}); + return LastfmSession.fromJson(response['session'] as Map); + } + + Future nowPlaying( + LastfmSession session, + Map track, + ) async => _request('track.updateNowPlaying', {...track, 'sk': session.key}); + + /// Successful responses include ignored scrobbles, which must also leave + /// the queue. A server failure throws and retains the entire batch. + Future scrobble( + LastfmSession session, + List> tracks, + ) async { + if (tracks.isEmpty || tracks.length > 50) { + throw ArgumentError.value(tracks.length, 'tracks', 'Expected 1 to 50'); + } + final parameters = {'sk': session.key}; + for (var i = 0; i < tracks.length; i++) { + for (final entry in tracks[i].entries) { + parameters['${entry.key}[$i]'] = entry.value; + } + } + final response = await _request('track.scrobble', parameters); + final result = response['scrobbles']; + if (result is! Map || result['@attr'] is! Map) { + throw const FormatException('Missing Last.fm scrobble result'); + } + final attributes = result['@attr'] as Map; + final accepted = int.tryParse('${attributes['accepted']}'); + final ignored = int.tryParse('${attributes['ignored']}'); + if (accepted == null || + ignored == null || + accepted + ignored != tracks.length) { + throw const FormatException('Incomplete Last.fm scrobble result'); + } + } + + void close() => _client.close(); +} diff --git a/lib/services/lastfm/lastfm_listening.dart b/lib/services/lastfm/lastfm_listening.dart new file mode 100644 index 000000000..be3369849 --- /dev/null +++ b/lib/services/lastfm/lastfm_listening.dart @@ -0,0 +1,153 @@ +import 'package:audio_service/audio_service.dart'; + +class LastfmTrack { + const LastfmTrack({ + required this.title, + required this.artist, + this.album = '', + this.duration, + }); + + factory LastfmTrack.fromJson(Map json) { + final seconds = int.tryParse('${json['duration']}'); + return LastfmTrack( + title: json['track'] as String, + artist: json['artist'] as String, + album: json['album'] as String? ?? '', + duration: seconds == null ? null : Duration(seconds: seconds), + ); + } + + final String title; + final String artist; + final String album; + final Duration? duration; + + Map toJson() => { + 'track': title, + 'artist': artist, + if (album.isNotEmpty) 'album': album, + if (duration != null) 'duration': '${duration!.inSeconds}', + }; +} + +/// Measures time spent playing, independently of the seek slider. The player +/// publishes a stable playback instance so repeat-one starts a new listen +/// while metadata updates, pause and seek retain the existing one. +class LastfmListening { + LastfmListening({ + required this.elapsed, + required this.now, + required this.onNowPlaying, + required this.onScrobble, + }); + + final Duration Function() elapsed; + final DateTime Function() now; + final void Function(LastfmTrack track) onNowPlaying; + final void Function(LastfmTrack track, DateTime started) onScrobble; + Object? _instance; + LastfmTrack? _track; + Duration? _mark; + Duration _listened = Duration.zero; + DateTime? _started; + bool _playing = false; + bool _submitted = false; + bool _announced = false; + + void update( + MediaItem? item, + PlaybackState state, { + required bool enabled, + String unknownTitle = 'Unknown title', + String unknownArtist = 'Unknown artist', + }) { + tick(); + final instance = item == null + ? null + : item.extras?['playbackInstance'] ?? item.id; + if (instance != _instance) { + reset(); + _instance = instance; + } + final title = item?.title.trim() ?? ''; + final artist = item?.artist?.trim() ?? ''; + _track = + title.isEmpty || + artist.isEmpty || + title == unknownTitle || + artist == unknownArtist + ? null + : LastfmTrack( + title: title, + artist: artist, + album: item?.album?.trim() ?? '', + duration: item?.duration, + ); + _playing = + enabled && + _track != null && + state.playing && + state.speed > 0 && + state.processingState == AudioProcessingState.ready; + _mark = elapsed(); + if (!state.playing) _announced = false; + if (_playing) { + _started ??= now().toUtc(); + if (!_announced) { + _announced = true; + onNowPlaying(_track!); + } + } + if (state.processingState == AudioProcessingState.completed || + state.processingState == AudioProcessingState.idle) { + reset(); + } else { + _submitIfEligible(); + } + } + + void tick() { + final mark = elapsed(); + if (_playing && _mark != null && mark > _mark!) { + _listened += mark - _mark!; + } + _mark = mark; + _submitIfEligible(); + } + + void _submitIfEligible() { + final track = _track; + final duration = track?.duration; + if (_submitted || + track == null || + _started == null || + duration == null || + duration <= const Duration(seconds: 30)) { + return; + } + final threshold = Duration( + microseconds: (duration.inMicroseconds ~/ 2).clamp( + 0, + const Duration(minutes: 4).inMicroseconds, + ), + ); + if (_listened >= threshold) { + _submitted = true; + onScrobble(track, _started!); + } + } + + void reset() { + _instance = null; + _track = null; + _mark = null; + _listened = Duration.zero; + _started = null; + _playing = false; + _submitted = false; + _announced = false; + } + + void resetAnnouncement() => _announced = false; +} diff --git a/lib/services/lastfm/lastfm_service.dart b/lib/services/lastfm/lastfm_service.dart new file mode 100644 index 000000000..15f9bfb31 --- /dev/null +++ b/lib/services/lastfm/lastfm_service.dart @@ -0,0 +1,465 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:audio_service/audio_service.dart'; +import 'package:flutter/foundation.dart'; +import 'package:mornye/services/lastfm/lastfm_api.dart'; +import 'package:mornye/services/lastfm/lastfm_listening.dart'; +import 'package:mornye/services/lastfm/lastfm_store.dart'; +import 'package:url_launcher/url_launcher.dart'; + +enum LastfmProblem { + connection, + storage, + pending, + expired, + reauthenticate, + unavailable, + rejected, +} + +/// Bound only to the local audio handler. Remote Link sessions and short +/// catalog previews never feed this service. +class LastfmService extends ChangeNotifier { + LastfmService({ + LastfmApi? api, + LastfmStore? store, + DateTime Function()? now, + Duration Function()? elapsed, + Future Function(Uri)? openBrowser, + }) : _api = api ?? LastfmApi(), + _store = store ?? LocalLastfmStore(), + _now = now ?? DateTime.now, + _elapsed = elapsed, + _openBrowser = openBrowser ?? _launch { + _clock.start(); + _listening = LastfmListening( + elapsed: () => _elapsed?.call() ?? _clock.elapsed, + now: _now, + onNowPlaying: (track) => unawaited(_announce(track)), + onScrobble: (track, started) => unawaited(_enqueue(track, started)), + ); + } + + static Future _launch(Uri url) => + launchUrl(url, mode: LaunchMode.externalApplication); + + final LastfmApi _api; + final LastfmStore _store; + final DateTime Function() _now; + final Duration Function()? _elapsed; + final Future Function(Uri) _openBrowser; + final _clock = Stopwatch(); + late final LastfmListening _listening; + final _subscriptions = >[]; + AudioHandler? _handler; + LastfmSession? _session; + String? _token; + DateTime? _tokenCreated; + final _queue = []; + Future? _initializing; + Future? _flushing; + Future _writes = Future.value(); + Timer? _ticker; + Timer? _retry; + bool _initialized = false; + bool _enabled = false; + bool _nowPlaying = true; + bool _busy = false; + bool _closed = false; + bool _durable = false; + int _generation = 0; + int _revision = 0; + LastfmProblem? _problem; + String Function() _unknownTitle = () => 'Unknown title'; + String Function() _unknownArtist = () => 'Unknown artist'; + + bool get configured => _api.credentials.configured; + bool get initialized => _initialized; + bool get connected => _session != null; + String? get username => _session?.username; + bool get enabled => _enabled; + bool get nowPlaying => _nowPlaying; + bool get busy => _busy; + bool get awaitingAuthorization => _token != null; + int get pendingCount => _queue.length; + LastfmProblem? get problem => _problem; + bool get _active => !_closed && configured && _enabled && connected; + + void _notify() { + if (!_closed) notifyListeners(); + } + + Future initialize() { + if (_closed || _initialized) return Future.value(); + return _initializing ??= _initialize(); + } + + Future _initialize() async { + try { + final saved = await _store.read(); + final session = await _store.readSession(); + if (_closed) return; + _enabled = saved.enabled; + _nowPlaying = saved.nowPlaying; + _queue.addAll(saved.queue); + _session = session; + _durable = true; + _initialized = true; + _problem = null; + _configure(); + unawaited(flush()); + } catch (_) { + _problem = LastfmProblem.storage; + } finally { + _initializing = null; + _notify(); + } + } + + void bind( + AudioHandler? handler, { + String Function()? unknownTitle, + String Function()? unknownArtist, + }) { + if (_closed || identical(_handler, handler)) return; + _listening.tick(); + _listening.reset(); + for (final subscription in _subscriptions) { + unawaited(subscription.cancel()); + } + _subscriptions.clear(); + _handler = handler; + if (unknownTitle != null) _unknownTitle = unknownTitle; + if (unknownArtist != null) _unknownArtist = unknownArtist; + if (handler != null) { + void update(Object? _) { + if (identical(handler, _handler)) _updateListening(); + } + + _subscriptions.add(handler.mediaItem.listen(update)); + _subscriptions.add(handler.playbackState.listen(update)); + } + unawaited(initialize()); + _updateListening(); + } + + void _updateListening() { + final handler = _handler; + _listening.update( + handler?.mediaItem.value, + handler?.playbackState.value ?? PlaybackState(), + enabled: _initialized && _active, + unknownTitle: _unknownTitle(), + unknownArtist: _unknownArtist(), + ); + } + + void _configure() { + _ticker?.cancel(); + _retry?.cancel(); + _ticker = null; + _retry = null; + _updateListening(); + if (!_active) return; + _ticker = Timer.periodic( + const Duration(seconds: 1), + (_) => _listening.tick(), + ); + _retry = Timer.periodic( + const Duration(seconds: 30), + (_) => unawaited(flush()), + ); + } + + Future beginConnection() async { + await initialize(); + if (_closed || _busy || !_initialized) return; + if (!configured) { + _problem = LastfmProblem.unavailable; + _notify(); + return; + } + final generation = ++_generation; + _busy = true; + _problem = null; + _notify(); + try { + final token = await _api.requestToken(); + if (_closed || generation != _generation) return; + _token = token; + _tokenCreated = _now(); + if (!await _openBrowser(_api.authorizationUrl(token))) { + throw StateError('Could not open Last.fm'); + } + } catch (_) { + if (!_closed && generation == _generation) { + _token = null; + _problem = LastfmProblem.connection; + } + } finally { + if (generation == _generation) _busy = false; + _notify(); + } + } + + Future finishConnection() async { + final token = _token; + if (_closed || _busy || token == null) return; + if (_now().difference(_tokenCreated!) >= const Duration(hours: 1)) { + cancelConnection(); + _problem = LastfmProblem.expired; + _notify(); + return; + } + final generation = _generation; + _busy = true; + _problem = null; + _notify(); + var savingSession = false; + try { + final session = await _api.session(token); + if (_closed || generation != _generation) return; + savingSession = true; + await _serialize(() => _store.writeSession(session)); + if (_closed || generation != _generation) return; + _session = session; + _token = null; + _enabled = true; + _listening.reset(); + await _save(); + _configure(); + unawaited(flush()); + } on LastfmException catch (error) { + if (!_closed && generation == _generation) { + _problem = error.code == 14 + ? LastfmProblem.pending + : error.code == 15 || error.code == 4 + ? LastfmProblem.expired + : LastfmProblem.connection; + if (_problem == LastfmProblem.expired) _token = null; + } + } catch (_) { + if (!_closed && generation == _generation) { + _problem = savingSession + ? LastfmProblem.storage + : LastfmProblem.connection; + } + } finally { + if (generation == _generation) _busy = false; + _notify(); + } + } + + void cancelConnection() { + _generation++; + _token = null; + _busy = false; + _problem = null; + _notify(); + } + + Future disconnect() async { + await initialize(); + if (_closed || !_initialized) return; + cancelConnection(); + _listening.reset(); + _session = null; + _enabled = false; + _queue.clear(); + _configure(); + try { + await _serialize(() => _store.writeSession(null)); + await _save(); + } catch (_) { + _problem = LastfmProblem.storage; + } + _notify(); + } + + Future setEnabled(bool value) async { + await initialize(); + if (_closed || !_initialized || !connected) return; + _listening.tick(); + _enabled = value; + _configure(); + await _saveSafely(); + if (value) unawaited(flush()); + } + + Future setNowPlaying(bool value) async { + await initialize(); + if (_closed || !_initialized) return; + _nowPlaying = value; + if (value) { + _listening.resetAnnouncement(); + _updateListening(); + } + await _saveSafely(); + } + + Future retry() async { + if (!_initialized) { + await initialize(); + return; + } + await _saveSafely(); + if (_durable) _configure(); + await flush(); + } + + Future _saveSafely() async { + try { + await _save(); + if (_problem == LastfmProblem.storage) _problem = null; + } catch (_) { + _problem = LastfmProblem.storage; + } + _notify(); + } + + Future _serialize(Future Function() write) { + final result = _writes.then((_) => write()); + _writes = result.catchError((Object _) {}); + return result; + } + + Future _save() async { + final revision = ++_revision; + _durable = false; + final enabled = _enabled, nowPlaying = _nowPlaying; + final queue = List.of(_queue); + await _serialize( + () => + _store.write(enabled: enabled, nowPlaying: nowPlaying, queue: queue), + ); + if (revision == _revision) _durable = true; + } + + Future _announce(LastfmTrack track) async { + final session = _session; + if (!_active || !_nowPlaying || session == null) return; + final generation = _generation; + try { + await _api.nowPlaying(session, track.toJson()); + } on LastfmException catch (error) { + if (error.code == 9) await _expiredSession(generation); + } catch (_) { + // Now Playing describes a live moment, so failed requests are not retried. + } + } + + Future _enqueue(LastfmTrack track, DateTime started) async { + final session = _session; + if (!_active || session == null) return; + final random = Random.secure().nextInt(1 << 32); + _queue.add( + LastfmScrobble( + id: '${started.microsecondsSinceEpoch}-$random', + username: session.username, + track: track, + started: started, + ), + ); + // Last.fm ignores timestamps older than two weeks. Bound disk usage too. + final oldest = _now().subtract(const Duration(days: 14)); + _queue.removeWhere((entry) => entry.started.isBefore(oldest)); + if (_queue.length > 2000) _queue.removeRange(0, _queue.length - 2000); + await _saveSafely(); + unawaited(flush()); + } + + Future flush() { + if (!_initialized || !_active || !_durable || _queue.isEmpty) { + return Future.value(); + } + return _flushing ??= _flush().whenComplete(() => _flushing = null); + } + + Future _flush() async { + while (_active && _durable) { + final session = _session!; + final generation = _generation; + final batch = _queue + .where((entry) => entry.username == session.username) + .take(50) + .toList(); + if (batch.isEmpty) return; + try { + await _api.scrobble( + session, + batch.map((entry) => entry.parameters).toList(), + ); + if (_closed) return; + final acknowledged = batch.map((entry) => entry.id).toSet(); + _queue.removeWhere((entry) => acknowledged.contains(entry.id)); + await _save(); + if (generation == _generation) _problem = null; + _notify(); + } on LastfmException catch (error) { + if (error.code == 9) { + await _expiredSession(generation); + } else if (!_closed && generation == _generation && !error.retryable) { + if (const {10, 13, 26}.contains(error.code)) { + _enabled = false; + _problem = LastfmProblem.unavailable; + _configure(); + } else { + final rejected = batch.map((entry) => entry.id).toSet(); + _queue.removeWhere((entry) => rejected.contains(entry.id)); + _problem = LastfmProblem.rejected; + } + await _saveSafely(); + } else if (!_closed && generation == _generation) { + _problem = LastfmProblem.connection; + _notify(); + } + return; + } catch (_) { + if (!_closed && generation == _generation) { + _problem = _durable + ? LastfmProblem.connection + : LastfmProblem.storage; + _notify(); + } + return; + } + } + } + + Future _expiredSession(int generation) async { + if (_closed || generation != _generation) return; + _generation++; + _busy = false; + _token = null; + _listening.reset(); + _session = null; + _enabled = false; + _problem = LastfmProblem.reauthenticate; + _configure(); + try { + await _serialize(() => _store.writeSession(null)); + await _save(); + } catch (_) { + _problem = LastfmProblem.storage; + } + _notify(); + } + + Future close() async { + if (_closed) return; + _listening.tick(); + _closed = true; + _generation++; + _ticker?.cancel(); + _retry?.cancel(); + for (final subscription in _subscriptions) { + unawaited(subscription.cancel()); + } + _subscriptions.clear(); + _api.close(); + await _writes; + _clock.stop(); + super.dispose(); + } +} diff --git a/lib/services/lastfm/lastfm_store.dart b/lib/services/lastfm/lastfm_store.dart new file mode 100644 index 000000000..37bba1d04 --- /dev/null +++ b/lib/services/lastfm/lastfm_store.dart @@ -0,0 +1,128 @@ +import 'dart:convert'; + +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:mornye/services/lastfm/lastfm_api.dart'; +import 'package:mornye/services/lastfm/lastfm_listening.dart'; +import 'package:mornye/services/secure_storage_options.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class LastfmScrobble { + const LastfmScrobble({ + required this.id, + required this.username, + required this.track, + required this.started, + }); + + factory LastfmScrobble.fromJson(Map json) => LastfmScrobble( + id: json['id'] as String, + username: json['username'] as String, + track: LastfmTrack.fromJson(json['track'] as Map), + started: DateTime.fromMillisecondsSinceEpoch( + (json['timestamp'] as int) * 1000, + isUtc: true, + ), + ); + + final String id; + final String username; + final LastfmTrack track; + final DateTime started; + + Map get parameters => { + ...track.toJson(), + 'timestamp': '${started.millisecondsSinceEpoch ~/ 1000}', + }; + + Map toJson() => { + 'id': id, + 'username': username, + 'track': track.toJson(), + 'timestamp': started.millisecondsSinceEpoch ~/ 1000, + }; +} + +abstract class LastfmStore { + Future readSession(); + Future writeSession(LastfmSession? session); + Future<({bool enabled, bool nowPlaying, List queue})> read(); + Future write({ + required bool enabled, + required bool nowPlaying, + required List queue, + }); +} + +class LocalLastfmStore implements LastfmStore { + LocalLastfmStore({ + Future Function()? preferences, + FlutterSecureStorage? storage, + }) : _preferences = preferences ?? SharedPreferences.getInstance, + _storage = + storage ?? + const FlutterSecureStorage( + aOptions: secureStorageAndroidOptions, + mOptions: secureStorageMacOsOptions, + ); + + static const _sessionKey = 'lastfm_session_v1'; + static const _stateKey = 'lastfm_scrobbles_v1'; + final Future Function() _preferences; + final FlutterSecureStorage _storage; + + @override + Future readSession() async { + final json = await _storage.read(key: _sessionKey); + if (json == null) return null; + return LastfmSession.fromJson(jsonDecode(json) as Map); + } + + @override + Future writeSession(LastfmSession? session) async { + if (session == null) { + await _storage.delete(key: _sessionKey); + } else { + await _storage.write( + key: _sessionKey, + value: jsonEncode(session.toJson()), + ); + } + } + + @override + Future<({bool enabled, bool nowPlaying, List queue})> + read() async { + final preferences = await _preferences(); + final raw = preferences.getString(_stateKey); + if (raw == null) { + return (enabled: false, nowPlaying: true, queue: []); + } + final json = jsonDecode(raw) as Map; + return ( + enabled: json['enabled'] == true, + nowPlaying: json['nowPlaying'] != false, + queue: [ + for (final entry in json['queue'] as List? ?? []) + LastfmScrobble.fromJson(entry as Map), + ], + ); + } + + @override + Future write({ + required bool enabled, + required bool nowPlaying, + required List queue, + }) async { + final preferences = await _preferences(); + final saved = await preferences.setString( + _stateKey, + jsonEncode({ + 'enabled': enabled, + 'nowPlaying': nowPlaying, + 'queue': queue.map((entry) => entry.toJson()).toList(), + }), + ); + if (!saved) throw StateError('Could not save Last.fm listening queue'); + } +} diff --git a/lib/services/music_player_automix.dart b/lib/services/music_player_automix.dart index afd343e6d..681c17cd0 100644 --- a/lib/services/music_player_automix.dart +++ b/lib/services/music_player_automix.dart @@ -421,6 +421,7 @@ class _MusicAutoMix { handler._pendingRestorePosition = null; rate = plan.rate; handler._runtime.personalization.begin(_learningTrack(next)); + handler._playbackInstance++; handler.mediaItem.add( handler ._toMediaItem( diff --git a/lib/services/music_player_gapless.dart b/lib/services/music_player_gapless.dart index 39de93792..e874beaf2 100644 --- a/lib/services/music_player_gapless.dart +++ b/lib/services/music_player_gapless.dart @@ -213,6 +213,7 @@ class _MusicGapless { handler._activeResolvedPath = _nextIsCopy ? path : null; handler._pendingRestorePosition = null; handler._runtime.personalization.begin(_learningTrack(next)); + handler._playbackInstance++; handler.mediaItem.add( handler ._toMediaItem(next, resolvedSource: _nextIsCopy ? path : null) diff --git a/lib/services/music_player_runtime.dart b/lib/services/music_player_runtime.dart index b5db352c7..fef29154e 100644 --- a/lib/services/music_player_runtime.dart +++ b/lib/services/music_player_runtime.dart @@ -21,6 +21,7 @@ import 'package:mornye/services/download_file_recovery.dart'; import 'package:mornye/services/library_collections_database.dart'; import 'package:mornye/services/library_database.dart'; import 'package:mornye/services/listening_statistics.dart'; +import 'package:mornye/services/lastfm/lastfm_service.dart'; import 'package:mornye/services/media_kit_playback_deck.dart'; import 'package:mornye/services/media_library_browser.dart'; import 'package:mornye/services/media_session_art_cache.dart'; @@ -255,6 +256,8 @@ class MusicPlayerRuntime { }) : _settings = settings; final PlaybackDependencies dependencies; + LastfmService? _lastfm; + LastfmService get lastfm => _lastfm ??= LastfmService(); AutoplayPersonalization? _personalization; // What learning observes also teaches [taste] what plays together and // [ranker] how much each part of a score counts. @@ -490,6 +493,7 @@ class MusicPlayerRuntime { void detach(MusicPlayerHandler handler) { if (!identical(_handler, handler)) return; + _lastfm?.bind(null); _unsubscribeSourceDeletion?.call(); _unsubscribeSourceDeletion = null; _unsubscribeSourceMetadata?.call(); @@ -536,6 +540,13 @@ class MusicPlayerRuntime { if (dependencies.isAndroid || dependencies.isIOS || isDesktopPlatform) { DiscordPresenceService.instance.bind(handler); } + if (isDesktopPlatform) { + lastfm.bind( + handler, + unknownTitle: () => unknownTitle, + unknownArtist: () => unknownArtist, + ); + } return handler; } catch (error, stack) { _log.e('Failed to initialize playback', error, stack); @@ -627,6 +638,7 @@ class MusicPlayerRuntime { _remoteSession?.dispose(); _remoteSession = null; await _handler?.dispose(); + await _lastfm?.close(); try { await _initFuture; } catch (_) { diff --git a/lib/services/music_player_service.dart b/lib/services/music_player_service.dart index 7bb2ec030..e549e4974 100644 --- a/lib/services/music_player_service.dart +++ b/lib/services/music_player_service.dart @@ -141,6 +141,7 @@ class MusicPlayerHandler extends BaseAudioHandler final List> _subscriptions = []; int _index = -1; int _playRequestGeneration = 0; + int _playbackInstance = 0; final _metadataChanges = {}; String? _activeResolvedPath; bool _disposed = false; @@ -318,13 +319,17 @@ class MusicPlayerHandler extends BaseAudioHandler } } - MediaItem _toMediaItem(PlayableMedia media, {String? resolvedSource}) => - media.toMediaItem( - resolvedSource: resolvedSource, - unknownTitle: _runtime.unknownTitle, - unknownArtist: _runtime.unknownArtist, - covers: _dependencies.coverStore, - ); + MediaItem _toMediaItem(PlayableMedia media, {String? resolvedSource}) { + final item = media.toMediaItem( + resolvedSource: resolvedSource, + unknownTitle: _runtime.unknownTitle, + unknownArtist: _runtime.unknownArtist, + covers: _dependencies.coverStore, + ); + return item.copyWith( + extras: {...?item.extras, 'playbackInstance': _playbackInstance}, + ); + } void _init() { if (_initialized) return; @@ -1637,6 +1642,7 @@ class MusicPlayerHandler extends BaseAudioHandler duration: media.duration, ); _runtime.personalization.begin(_learningTrack(media)); + _playbackInstance++; mediaItem.add(_toMediaItem(media)); _lastBroadcastPosition = Duration.zero; _lastPositionBroadcastAt = null; diff --git a/lib/utils/settings_search_catalog.dart b/lib/utils/settings_search_catalog.dart index 865b56e78..75ab0e2b7 100644 --- a/lib/utils/settings_search_catalog.dart +++ b/lib/utils/settings_search_catalog.dart @@ -240,6 +240,13 @@ class SettingsSearchCatalog { ), ], playback = [ + if (isDesktopPlatform) + SettingsSearchEntry( + icon: Icons.history_rounded, + title: 'Last.fm', + subtitle: l10n.lastfmDescription, + keywords: const ['lastfm', 'scrobble', 'scrobbling', 'now playing'], + ), SettingsSearchEntry( icon: Icons.equalizer, title: l10n.equalizerTitle, diff --git a/lib/widgets/lastfm_settings.dart b/lib/widgets/lastfm_settings.dart new file mode 100644 index 000000000..1076d0395 --- /dev/null +++ b/lib/widgets/lastfm_settings.dart @@ -0,0 +1,124 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:mornye/l10n/l10n.dart'; +import 'package:mornye/services/lastfm/lastfm_service.dart'; +import 'package:mornye/widgets/settings_group.dart'; + +class LastfmSettings extends StatefulWidget { + const LastfmSettings({super.key, required this.service}); + + final LastfmService service; + + @override + State createState() => _LastfmSettingsState(); +} + +class _LastfmSettingsState extends State { + @override + void initState() { + super.initState(); + unawaited(widget.service.initialize()); + } + + @override + void didUpdateWidget(LastfmSettings oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.service != widget.service) { + unawaited(widget.service.initialize()); + } + } + + @override + Widget build(BuildContext context) { + final service = widget.service; + final l10n = context.l10n; + return ListenableBuilder( + listenable: service, + builder: (context, _) => SettingsGroup( + children: [ + SettingsItem( + icon: service.connected ? Icons.check_circle_outline : Icons.link, + title: service.connected + ? service.username! + : service.busy + ? l10n.lastfmConnecting + : service.awaitingAuthorization + ? l10n.lastfmFinishConnection + : l10n.lastfmConnect, + subtitle: !service.configured + ? l10n.lastfmUnavailable + : service.awaitingAuthorization + ? l10n.lastfmAuthorizeHelp + : l10n.lastfmDescription, + onTap: service.busy || !service.configured || service.connected + ? null + : () => unawaited( + service.awaitingAuthorization + ? service.finishConnection() + : service.beginConnection(), + ), + showDivider: + service.connected || + service.awaitingAuthorization || + service.problem != null, + ), + if (service.awaitingAuthorization) + SettingsItem( + icon: Icons.close, + title: l10n.dialogCancel, + onTap: service.cancelConnection, + showDivider: service.problem != null, + ), + if (service.connected) ...[ + SettingsSwitchItem( + icon: Icons.history_rounded, + title: l10n.lastfmScrobbling, + subtitle: l10n.lastfmScrobblingDescription, + value: service.enabled, + onChanged: (enabled) => unawaited(service.setEnabled(enabled)), + ), + SettingsSwitchItem( + icon: Icons.music_note_outlined, + title: l10n.lastfmNowPlaying, + subtitle: l10n.lastfmNowPlayingDescription, + value: service.nowPlaying, + enabled: service.enabled, + onChanged: (enabled) => unawaited(service.setNowPlaying(enabled)), + ), + ], + if (service.pendingCount > 0) + SettingsItem( + icon: Icons.sync, + title: l10n.lastfmPending(service.pendingCount), + onTap: service.enabled ? () => unawaited(service.flush()) : null, + ), + if (service.problem case final problem?) + SettingsItem( + icon: Icons.info_outline, + title: switch (problem) { + LastfmProblem.connection => l10n.lastfmConnectionError, + LastfmProblem.storage => l10n.lastfmStorageError, + LastfmProblem.pending => l10n.lastfmAuthorizationPending, + LastfmProblem.expired => l10n.lastfmAuthorizationExpired, + LastfmProblem.reauthenticate => l10n.lastfmReauthenticate, + LastfmProblem.unavailable => l10n.lastfmUnavailable, + LastfmProblem.rejected => l10n.lastfmRejected, + }, + onTap: problem == LastfmProblem.storage + ? () => unawaited(service.retry()) + : null, + showDivider: service.connected, + ), + if (service.connected) + SettingsItem( + icon: Icons.link_off, + title: l10n.lastfmDisconnect, + onTap: () => unawaited(service.disconnect()), + showDivider: false, + ), + ], + ), + ); + } +} diff --git a/test/lastfm_api_test.dart b/test/lastfm_api_test.dart new file mode 100644 index 000000000..d448cec2a --- /dev/null +++ b/test/lastfm_api_test.dart @@ -0,0 +1,194 @@ +import 'dart:convert'; + +import 'package:crypto/crypto.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:mornye/services/lastfm/lastfm_api.dart'; + +void main() { + const credentials = LastfmCredentials( + apiKey: 'app-key', + apiSecret: 'app-secret', + ); + + test('signature sorts ASCII keys and signs UTF-8 before URL encoding', () { + final parameters = { + 'track[1]': 'Jóga', + 'artist[1]': 'Björk', + 'track[10]': '十', + 'method': 'track.scrobble', + 'format': 'json', + 'callback': 'ignored', + }; + final expected = md5 + .convert( + utf8.encode( + 'artist[1]Björkmethodtrack.scrobbletrack[10]十track[1]Jógaapp-secret', + ), + ) + .toString(); + expect(lastfmSignature(parameters, credentials.apiSecret), expected); + }); + + test('token and session requests use HTTPS and signed form bodies', () async { + final requests = []; + final api = LastfmApi( + credentials: credentials, + client: MockClient((request) async { + requests.add(request); + if (request.bodyFields['method'] == 'auth.getToken') { + return http.Response('{"token":"request-token"}', 200); + } + return http.Response( + '{"session":{"name":"listener","key":"session-key"}}', + 200, + ); + }), + ); + addTearDown(api.close); + final token = await api.requestToken(); + expect(api.authorizationUrl(token).queryParameters, { + 'api_key': 'app-key', + 'token': token, + }); + final session = await api.session(token); + expect(session.username, 'listener'); + for (final request in requests) { + expect(request.method, 'POST'); + expect(request.url.toString(), 'https://ws.audioscrobbler.com/2.0/'); + expect(request.url.query, isEmpty); + expect( + request.bodyFields['api_sig'], + lastfmSignature(request.bodyFields, 'app-secret'), + ); + } + }); + + test( + 'a 200 response can reject a session without leaking credentials', + () async { + final api = LastfmApi( + credentials: credentials, + client: MockClient( + (_) async => http.Response( + '{"error":9,"message":"private-response-session-key"}', + 200, + ), + ), + ); + addTearDown(api.close); + await expectLater( + api.session('private-request-token'), + throwsA( + isA() + .having((error) => error.code, 'code', 9) + .having( + (error) => error.toString(), + 'message', + isNot(contains('private')), + ), + ), + ); + }, + ); + + test( + 'scrobble batches retain start timestamps and distinguish ignored plays', + () async { + late Map sent; + final api = LastfmApi( + credentials: credentials, + client: MockClient((request) async { + sent = request.bodyFields; + return http.Response( + '{"scrobbles":{"@attr":{"accepted":"1","ignored":"1"}}}', + 200, + ); + }), + ); + addTearDown(api.close); + await api.scrobble( + const LastfmSession(username: 'listener', key: 'session-key'), + [ + {'track': 'First', 'artist': 'Artist', 'timestamp': '1700000000'}, + {'track': 'Second', 'artist': 'Artist', 'timestamp': '1700000100'}, + ], + ); + expect(sent['timestamp[0]'], '1700000000'); + expect(sent['timestamp[1]'], '1700000100'); + expect(sent['sk'], 'session-key'); + expect(sent.keys, isNot(contains('username'))); + }, + ); + + test( + 'incomplete acknowledgement is not treated as a successful batch', + () async { + final api = LastfmApi( + credentials: credentials, + client: MockClient( + (_) async => http.Response( + '{"scrobbles":{"@attr":{"accepted":"0","ignored":"0"}}}', + 200, + ), + ), + ); + addTearDown(api.close); + await expectLater( + api.scrobble(const LastfmSession(username: 'listener', key: 'key'), [ + {'track': 'Song', 'artist': 'Artist', 'timestamp': '1700000000'}, + ]), + throwsFormatException, + ); + }, + ); + + test('unconfigured builds make no network requests', () async { + final api = LastfmApi( + credentials: const LastfmCredentials(apiKey: '', apiSecret: ''), + client: MockClient((_) async => fail('Unexpected network request')), + ); + addTearDown(api.close); + await expectLater(api.requestToken(), throwsA(isA())); + }); + + test( + 'HTTP service outages and rate limiting are retryable even without JSON', + () async { + for (final status in [429, 500, 503]) { + final api = LastfmApi( + credentials: credentials, + client: MockClient( + (_) async => http.Response('Unavailable', status), + ), + ); + addTearDown(api.close); + await expectLater( + api.requestToken(), + throwsA( + isA().having( + (error) => error.retryable, + 'retryable', + isTrue, + ), + ), + ); + } + }, + ); + + test( + 'non-API HTTP errors do not reject otherwise valid cached scrobbles', + () async { + final api = LastfmApi( + credentials: credentials, + client: MockClient( + (_) async => http.Response('Proxy unavailable', 403), + ), + ); + addTearDown(api.close); + await expectLater(api.requestToken(), throwsFormatException); + }, + ); +} diff --git a/test/lastfm_listening_test.dart b/test/lastfm_listening_test.dart new file mode 100644 index 000000000..42c0e930b --- /dev/null +++ b/test/lastfm_listening_test.dart @@ -0,0 +1,179 @@ +import 'package:audio_service/audio_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mornye/services/lastfm/lastfm_listening.dart'; + +void main() { + late Duration elapsed; + late LastfmListening listening; + late List announcements; + late List<(LastfmTrack, DateTime)> scrobbles; + final start = DateTime.utc(2026, 11, 1, 12); + MediaItem track({ + int instance = 1, + int? seconds = 240, + String artist = 'Artist', + }) => MediaItem( + id: 'file:///private/song.flac', + title: 'Song', + artist: artist, + album: 'Album', + duration: seconds == null ? null : Duration(seconds: seconds), + extras: {'playbackInstance': instance}, + ); + PlaybackState state({ + bool playing = true, + bool buffering = false, + int position = 0, + }) => PlaybackState( + playing: playing, + processingState: buffering + ? AudioProcessingState.buffering + : AudioProcessingState.ready, + updatePosition: Duration(seconds: position), + ); + + setUp(() { + elapsed = Duration.zero; + announcements = []; + scrobbles = []; + listening = LastfmListening( + elapsed: () => elapsed, + now: () => start.add(elapsed), + onNowPlaying: announcements.add, + onScrobble: (track, timestamp) => scrobbles.add((track, timestamp)), + ); + }); + + test('scrobbles at half duration once, with original UTC start time', () { + listening.update(track(), state(), enabled: true); + expect(announcements, hasLength(1)); + elapsed = const Duration(seconds: 119); + listening.tick(); + expect(scrobbles, isEmpty); + elapsed = const Duration(seconds: 120); + listening.tick(); + expect(scrobbles.single.$2, start); + expect(scrobbles.single.$1.toJson(), { + 'track': 'Song', + 'artist': 'Artist', + 'album': 'Album', + 'duration': '240', + }); + elapsed = const Duration(minutes: 10); + listening.tick(); + expect(scrobbles, hasLength(1)); + }); + + test('seeking does not add listening time or begin another play', () { + listening.update(track(), state(), enabled: true); + elapsed = const Duration(seconds: 10); + listening.update(track(), state(position: 230), enabled: true); + expect(scrobbles, isEmpty); + elapsed = const Duration(seconds: 20); + listening.update(track(), state(position: 0), enabled: true); + expect(announcements, hasLength(1)); + elapsed = const Duration(seconds: 120); + listening.tick(); + expect(scrobbles, hasLength(1)); + }); + + test( + 'pause and buffering stop accrual; resume keeps the listening total', + () { + listening.update(track(), state(), enabled: true); + elapsed = const Duration(seconds: 40); + listening.update(track(), state(playing: false), enabled: true); + elapsed = const Duration(minutes: 10); + listening.update(track(), state(buffering: true), enabled: true); + elapsed += const Duration(seconds: 30); + listening.update(track(), state(), enabled: true); + elapsed += const Duration(seconds: 79); + listening.tick(); + expect(scrobbles, isEmpty); + elapsed += const Duration(seconds: 1); + listening.tick(); + expect(scrobbles, hasLength(1)); + expect(scrobbles.single.$2, start); + expect(announcements, hasLength(2)); + }, + ); + + test('short songs are excluded; long songs qualify after four minutes', () { + listening.update(track(seconds: 30), state(), enabled: true); + elapsed = const Duration(minutes: 10); + listening.tick(); + expect(scrobbles, isEmpty); + listening.update(track(instance: 2, seconds: 900), state(), enabled: true); + elapsed += const Duration(seconds: 239); + listening.tick(); + expect(scrobbles, isEmpty); + elapsed += const Duration(seconds: 1); + listening.tick(); + expect(scrobbles, hasLength(1)); + }); + + test('metadata updates preserve a play and late duration can qualify it', () { + listening.update(track(seconds: null), state(), enabled: true); + elapsed = const Duration(seconds: 120); + listening.update(track(), state(), enabled: true); + expect(scrobbles, hasLength(1)); + listening.update( + track().copyWith(title: 'Edited title'), + state(), + enabled: true, + ); + elapsed += const Duration(seconds: 120); + listening.tick(); + expect(scrobbles, hasLength(1)); + expect(announcements, hasLength(1)); + }); + + test('repeat-one is a separate listen even with the same media ID', () { + listening.update(track(), state(), enabled: true); + elapsed = const Duration(seconds: 120); + listening.tick(); + listening.update(track(instance: 2), state(), enabled: true); + elapsed += const Duration(seconds: 120); + listening.tick(); + expect(scrobbles, hasLength(2)); + expect(scrobbles.last.$2, start.add(const Duration(seconds: 120))); + expect(announcements, hasLength(2)); + }); + + test('restored paused position and disabled time are not scrobbled', () { + listening.update( + track(), + state(playing: false, position: 200), + enabled: true, + ); + elapsed = const Duration(minutes: 20); + listening.update(track(), state(position: 200), enabled: false); + elapsed += const Duration(minutes: 10); + listening.update(track(), state(position: 200), enabled: true); + expect(scrobbles, isEmpty); + elapsed += const Duration(seconds: 120); + listening.tick(); + expect(scrobbles.single.$2, start.add(const Duration(minutes: 30))); + listening.update(track(), state(), enabled: false); + listening.update(track(), state(), enabled: true); + elapsed += const Duration(seconds: 120); + listening.tick(); + expect(scrobbles, hasLength(1)); + }); + + test('missing and localized unknown metadata never leaves the player', () { + listening.update(track(artist: ''), state(), enabled: true); + elapsed = const Duration(minutes: 5); + listening.tick(); + listening.update( + track(artist: 'Artis tidak dikenal'), + state(), + enabled: true, + unknownArtist: 'Artis tidak dikenal', + ); + elapsed += const Duration(minutes: 5); + listening.tick(); + expect(announcements, isEmpty); + expect(scrobbles, isEmpty); + }); +} diff --git a/test/lastfm_service_test.dart b/test/lastfm_service_test.dart new file mode 100644 index 000000000..d354cd1e3 --- /dev/null +++ b/test/lastfm_service_test.dart @@ -0,0 +1,397 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:audio_service/audio_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mornye/services/lastfm/lastfm_api.dart'; +import 'package:mornye/services/lastfm/lastfm_service.dart'; + +import 'support/lastfm_fakes.dart'; + +void main() { + final services = []; + void serviceTest( + String description, + Future Function(WidgetTester) body, + ) { + testWidgets(description, (tester) async { + try { + await body(tester); + } finally { + for (final service in services.reversed) { + final closing = service.close(); + await tester.pump(); + await closing; + } + services.clear(); + } + }); + } + + final song = MediaItem( + id: 'file:///private/music.flac', + title: 'Song', + artist: 'Artist', + album: 'Album', + duration: const Duration(minutes: 4), + extras: const {'playbackInstance': 1}, + ); + PlaybackState playing({bool play = true}) => + PlaybackState(playing: play, processingState: AudioProcessingState.ready); + + LastfmService create( + WidgetTester tester, + FakeLastfmApi api, + MemoryLastfmStore store, { + Future Function(Uri)? openBrowser, + }) { + final start = tester.binding.clock.now(); + final service = LastfmService( + api: api, + store: store, + now: tester.binding.clock.now, + elapsed: () => tester.binding.clock.now().difference(start), + openBrowser: openBrowser ?? (_) async => true, + ); + services.add(service); + return service; + } + + serviceTest('local playback persists a qualified listen before submission', ( + tester, + ) async { + final api = FakeLastfmApi(), store = MemoryLastfmStore(); + final persistedSizes = []; + api.onBatch = () => persistedSizes.add(store.queue.length); + final service = create(tester, api, store); + await service.initialize(); + final handler = BaseAudioHandler(); + service.bind(handler); + handler.mediaItem.add(song); + handler.playbackState.add(playing()); + await tester.pump(); + expect(api.announcements.single['track'], 'Song'); + expect(api.announcements.single.toString(), isNot(contains('/private/'))); + await tester.pump(const Duration(seconds: 120)); + await service.flush(); + expect(api.batches, hasLength(1)); + expect(persistedSizes, [1]); + expect(api.batches.single.single.keys, isNot(contains('id'))); + expect(store.queue, isEmpty); + expect(service.pendingCount, 0); + await tester.pump(const Duration(minutes: 4)); + expect(api.batches, hasLength(1)); + }); + + serviceTest('offline queue survives restart and keeps original timestamps', ( + tester, + ) async { + final store = MemoryLastfmStore(); + final offline = FakeLastfmApi() + ..batchError = const SocketException('offline'); + final first = create(tester, offline, store); + await first.initialize(); + final handler = BaseAudioHandler(); + first.bind(handler); + handler.mediaItem.add(song); + handler.playbackState.add(playing()); + await tester.pump(); + await tester.pump(const Duration(seconds: 120)); + await first.flush(); + expect(store.queue, hasLength(1)); + final timestamp = store.queue.single.parameters['timestamp']; + await first.close(); + final online = FakeLastfmApi(); + final second = create(tester, online, store); + await second.initialize(); + await second.flush(); + expect(online.batches.single.single['timestamp'], timestamp); + expect(store.queue, isEmpty); + }); + + serviceTest( + 'cached batches stay ordered, are limited to 50 and do not overlap', + (tester) async { + final store = MemoryLastfmStore() + ..queue = [for (var i = 0; i < 101; i++) lastfmQueued(i)]; + final gate = Completer(); + final api = FakeLastfmApi()..batchGate = gate; + final service = create(tester, api, store); + await service.initialize(); + final flush = service.flush(); + final concurrent = service.flush(); + await tester.pump(); + expect(api.batches, hasLength(1)); + gate.complete(); + await Future.wait([flush, concurrent]); + expect(api.batches.map((batch) => batch.length), [50, 50, 1]); + expect( + api.batches.first.first['timestamp'], + lastfmQueued(0).parameters['timestamp'], + ); + expect(store.queue, isEmpty); + }, + ); + + serviceTest( + 'scrobbling opt-out makes no requests and excludes elapsed time', + (tester) async { + final store = MemoryLastfmStore()..enabled = false; + final api = FakeLastfmApi(); + final service = create(tester, api, store); + await service.initialize(); + final handler = BaseAudioHandler(); + service.bind(handler); + handler.mediaItem.add(song); + handler.playbackState.add(playing()); + await tester.pump(const Duration(minutes: 10)); + expect(api.announcements, isEmpty); + expect(api.batches, isEmpty); + await service.setEnabled(true); + await tester.pump(const Duration(seconds: 119)); + expect(api.batches, isEmpty); + await tester.pump(const Duration(seconds: 1)); + await service.flush(); + expect(api.batches, hasLength(1)); + }, + ); + + serviceTest( + 'Now Playing can be switched off independently and failures are not retried', + (tester) async { + final store = MemoryLastfmStore()..nowPlaying = false; + final api = FakeLastfmApi() + ..announceError = const SocketException('offline'); + final service = create(tester, api, store); + await service.initialize(); + final handler = BaseAudioHandler(); + service.bind(handler); + handler.mediaItem.add(song); + handler.playbackState.add(playing()); + await tester.pump(); + expect(api.announcements, isEmpty); + await service.setNowPlaying(true); + expect(api.announcements, hasLength(1)); + await tester.pump(const Duration(minutes: 2)); + await service.flush(); + expect(api.announcements, hasLength(1)); + expect(api.batches, hasLength(1)); + }, + ); + + serviceTest('browser approval is required and session is stored separately', ( + tester, + ) async { + final store = MemoryLastfmStore()..session = null; + final api = FakeLastfmApi()..sessionError = const LastfmException(14); + Uri? browser; + final service = create( + tester, + api, + store, + openBrowser: (url) async { + browser = url; + return true; + }, + ); + await service.beginConnection(); + expect(browser?.host, 'www.last.fm'); + expect(service.awaitingAuthorization, isTrue); + await service.finishConnection(); + expect(service.connected, isFalse); + expect(service.problem, LastfmProblem.pending); + api.sessionError = null; + await service.finishConnection(); + expect(service.connected, isTrue); + expect(store.session?.key, lastfmTestSession.key); + expect(service.enabled, isTrue); + expect(service.busy, isFalse); + expect(service.awaitingAuthorization, isFalse); + }); + + serviceTest( + 'expired approval can be restarted and browser failure can recover', + (tester) async { + final store = MemoryLastfmStore()..session = null; + final api = FakeLastfmApi(); + var opened = false; + final service = create( + tester, + api, + store, + openBrowser: (_) async => opened, + ); + await service.beginConnection(); + expect(service.problem, LastfmProblem.connection); + expect(service.awaitingAuthorization, isFalse); + opened = true; + await service.beginConnection(); + await tester.pump(const Duration(hours: 1)); + await service.finishConnection(); + expect(service.problem, LastfmProblem.expired); + expect(service.connected, isFalse); + await service.beginConnection(); + await service.finishConnection(); + expect(service.connected, isTrue); + }, + ); + + serviceTest('cancelled login cannot publish a late session', (tester) async { + final store = MemoryLastfmStore()..session = null; + final result = Completer(); + final api = FakeLastfmApi()..sessionResult = result; + final service = create(tester, api, store); + await service.beginConnection(); + final finish = service.finishConnection(); + service.cancelConnection(); + result.complete(lastfmTestSession); + await finish; + expect(service.connected, isFalse); + expect(store.session, isNull); + }); + + serviceTest( + 'network failure during approval can be retried without a new token', + (tester) async { + final api = FakeLastfmApi() + ..sessionError = const SocketException('offline'); + final service = create(tester, api, MemoryLastfmStore()..session = null); + await service.beginConnection(); + await service.finishConnection(); + expect(service.problem, LastfmProblem.connection); + expect(service.awaitingAuthorization, isTrue); + api.sessionError = null; + await service.finishConnection(); + expect(service.connected, isTrue); + expect(api.tokenRequests, 1); + }, + ); + + serviceTest('disconnect wins over a pending secure-storage write', ( + tester, + ) async { + final gate = Completer(); + final store = MemoryLastfmStore()..session = null; + final service = create(tester, FakeLastfmApi(), store); + await service.beginConnection(); + store.sessionGate = gate; + final finish = service.finishConnection(); + await tester.pump(); + final disconnect = service.disconnect(); + await tester.pump(); + gate.complete(); + await Future.wait([finish, disconnect]); + expect(store.session, isNull); + expect(service.connected, isFalse); + expect(service.enabled, isFalse); + }); + + serviceTest('only the connected account receives cached scrobbles', ( + tester, + ) async { + final store = MemoryLastfmStore() + ..queue = [lastfmQueued(1), lastfmQueued(2, username: 'other')]; + final api = FakeLastfmApi(); + final service = create(tester, api, store); + await service.initialize(); + await service.flush(); + expect(api.batches.single, hasLength(1)); + expect(api.accounts.single, 'listener'); + expect(store.queue.single.username, 'other'); + await service.disconnect(); + expect(store.queue, isEmpty); + expect(store.session, isNull); + }); + + serviceTest( + 'session revocation retains pending plays and stops automatic submission', + (tester) async { + final store = MemoryLastfmStore()..queue = [lastfmQueued(1)]; + final api = FakeLastfmApi()..batchError = const LastfmException(9); + final service = create(tester, api, store); + await service.initialize(); + await service.flush(); + expect(service.problem, LastfmProblem.reauthenticate); + expect(service.connected, isFalse); + expect(store.queue, hasLength(1)); + expect(store.session, isNull); + await tester.pump(const Duration(minutes: 5)); + expect(api.batches, hasLength(1)); + api.batchError = null; + await service.beginConnection(); + await service.finishConnection(); + await service.flush(); + expect(store.queue, isEmpty); + }, + ); + + serviceTest( + 'permanent errors are not retried, temporary errors remain queued', + (tester) async { + for (final code in [6, 11, 16, 29]) { + final store = MemoryLastfmStore()..queue = [lastfmQueued(code)]; + final api = FakeLastfmApi()..batchError = LastfmException(code); + final service = create(tester, api, store); + await service.initialize(); + await service.flush(); + expect(store.queue.length, code == 6 ? 0 : 1); + await tester.pump(const Duration(seconds: 30)); + expect(api.batches.length, code == 6 ? 1 : 2); + await service.close(); + } + }, + ); + + serviceTest( + 'failed storage prevents submission and recovers without losing the queue', + (tester) async { + final store = MemoryLastfmStore()..failRead = true; + final api = FakeLastfmApi(); + final service = create(tester, api, store); + await service.initialize(); + expect(service.problem, LastfmProblem.storage); + expect(store.writes, 0); + store.failRead = false; + await service.retry(); + final handler = BaseAudioHandler(); + service.bind(handler); + handler.mediaItem.add(song); + handler.playbackState.add(playing()); + await tester.pump(); + store.failWrite = true; + await tester.pump(const Duration(seconds: 120)); + expect(api.batches, isEmpty); + expect(service.pendingCount, 1); + store.failWrite = false; + await service.retry(); + expect(api.batches, hasLength(1)); + expect(store.queue, isEmpty); + }, + ); + + serviceTest( + 'unbind stops counting and configured credentials are required to connect', + (tester) async { + final api = FakeLastfmApi(); + final service = create(tester, api, MemoryLastfmStore()); + await service.initialize(); + final handler = BaseAudioHandler(); + service.bind(handler); + handler.mediaItem.add(song); + handler.playbackState.add(playing()); + await tester.pump(const Duration(seconds: 20)); + service.bind(null); + await tester.pump(const Duration(minutes: 10)); + expect(api.batches, isEmpty); + final unavailableApi = FakeLastfmApi(configured: false); + final unavailable = create( + tester, + unavailableApi, + MemoryLastfmStore()..session = null, + ); + await unavailable.beginConnection(); + expect(unavailable.problem, LastfmProblem.unavailable); + expect(unavailableApi.tokenRequests, 0); + }, + ); +} diff --git a/test/lastfm_settings_test.dart b/test/lastfm_settings_test.dart new file mode 100644 index 000000000..beba60958 --- /dev/null +++ b/test/lastfm_settings_test.dart @@ -0,0 +1,111 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mornye/l10n/l10n.dart'; +import 'package:mornye/services/lastfm/lastfm_service.dart'; +import 'package:mornye/theme/app_theme.dart'; +import 'package:mornye/theme/mornye_theme.dart'; +import 'package:mornye/widgets/lastfm_settings.dart'; +import 'package:mornye/widgets/settings_group.dart'; + +import 'support/lastfm_fakes.dart'; + +void main() { + for (final mornye in [false, true]) { + testWidgets( + 'Last.fm account and playback controls follow the selected style ($mornye)', + (tester) async { + final store = MemoryLastfmStore()..session = null; + final api = FakeLastfmApi(); + final opened = []; + final service = LastfmService( + api: api, + store: store, + openBrowser: (url) async { + opened.add(url); + return true; + }, + ); + try { + await tester.pumpWidget( + MaterialApp( + theme: mornye + ? MornyeTheme.build(Brightness.dark) + : AppTheme.dark(), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SingleChildScrollView( + child: MornyeSettingsTheme( + child: LastfmSettings(service: service), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Connect Last.fm')); + await tester.pumpAndSettle(); + expect(opened.single.host, 'www.last.fm'); + expect(find.text('Finish connecting'), findsOneWidget); + await tester.tap(find.text('Finish connecting')); + await tester.pumpAndSettle(); + expect(find.text('listener'), findsOneWidget); + expect(find.text('Disconnect Last.fm'), findsOneWidget); + final switches = tester + .widgetList(find.byType(SettingsSwitchItem)) + .toList(); + expect(switches.map((widget) => widget.title), [ + 'Scrobbling', + 'Show Now Playing', + ]); + switches.first.onChanged!(false); + await tester.pumpAndSettle(); + expect(service.enabled, isFalse); + await tester.tap(find.text('Disconnect Last.fm')); + await tester.pumpAndSettle(); + expect(find.text('Connect Last.fm'), findsOneWidget); + expect(store.session, isNull); + expect(tester.takeException(), isNull); + } finally { + await tester.pumpWidget(const SizedBox.shrink()); + final closing = service.close(); + await tester.pump(); + await closing; + } + }, + ); + } + + testWidgets( + 'unconfigured builds explain availability without exposing developer fields', + (tester) async { + final api = FakeLastfmApi(configured: false); + final service = LastfmService( + api: api, + store: MemoryLastfmStore()..session = null, + ); + try { + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: LastfmSettings(service: service)), + ), + ); + await tester.pumpAndSettle(); + expect( + find.text('Last.fm is unavailable in this build.'), + findsOneWidget, + ); + await tester.tap(find.text('Connect Last.fm')); + expect(api.tokenRequests, 0); + expect(find.byType(TextField), findsNothing); + } finally { + await tester.pumpWidget(const SizedBox.shrink()); + final closing = service.close(); + await tester.pump(); + await closing; + } + }, + ); +} diff --git a/test/lastfm_store_test.dart b/test/lastfm_store_test.dart new file mode 100644 index 000000000..8059ae893 --- /dev/null +++ b/test/lastfm_store_test.dart @@ -0,0 +1,56 @@ +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mornye/services/lastfm/lastfm_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'support/lastfm_fakes.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + SharedPreferences.setMockInitialValues({}); + FlutterSecureStorage.setMockInitialValues({}); + }); + + test( + 'account session stays in secure storage, outside preferences and queue', + () async { + final store = LocalLastfmStore(); + await store.writeSession(lastfmTestSession); + await store.write( + enabled: true, + nowPlaying: false, + queue: [lastfmQueued(1)], + ); + final restored = LocalLastfmStore(); + expect((await restored.readSession())?.key, lastfmTestSession.key); + final state = await restored.read(); + expect(state.enabled, isTrue); + expect(state.nowPlaying, isFalse); + expect(state.queue.single.parameters, lastfmQueued(1).parameters); + final preferences = await SharedPreferences.getInstance(); + for (final key in preferences.getKeys()) { + expect( + '${preferences.get(key)}', + isNot(contains(lastfmTestSession.key)), + ); + } + await restored.writeSession(null); + expect(await store.readSession(), isNull); + }, + ); + + test( + 'new installations opt out and malformed state is not overwritten', + () async { + final store = LocalLastfmStore(); + expect((await store.read()).enabled, isFalse); + expect(await store.readSession(), isNull); + final preferences = await SharedPreferences.getInstance(); + await preferences.setString('lastfm_scrobbles_v1', 'invalid'); + await expectLater(store.read(), throwsFormatException); + expect(preferences.getString('lastfm_scrobbles_v1'), 'invalid'); + }, + ); +} diff --git a/test/music_player_runtime_test.dart b/test/music_player_runtime_test.dart index 372d2fb35..c736b5baf 100644 --- a/test/music_player_runtime_test.dart +++ b/test/music_player_runtime_test.dart @@ -651,6 +651,25 @@ const _track = PlayableMedia( void main() { TestWidgetsFlutterBinding.ensureInitialized(); + test( + 'playback instances survive pause and seek but change for repeated songs', + () async { + final handler = await _runtime().initialize(); + await handler.setQueueAndPlay([_track, _track]); + final first = handler.mediaItem.value!.extras!['playbackInstance']; + await handler.pause(); + await handler.play(); + await handler.seek(Duration.zero); + expect(handler.mediaItem.value!.extras!['playbackInstance'], first); + await handler.skipToQueueItem(1); + expect(handler.mediaItem.value!.id, _track.id); + expect( + handler.mediaItem.value!.extras!['playbackInstance'], + isNot(first), + ); + }, + ); + test( 'Android updates every queued copy before playing a moved download', () async { diff --git a/test/support/lastfm_fakes.dart b/test/support/lastfm_fakes.dart new file mode 100644 index 000000000..19588b1ba --- /dev/null +++ b/test/support/lastfm_fakes.dart @@ -0,0 +1,114 @@ +import 'dart:async'; + +import 'package:mornye/services/lastfm/lastfm_api.dart'; +import 'package:mornye/services/lastfm/lastfm_listening.dart'; +import 'package:mornye/services/lastfm/lastfm_store.dart'; + +const lastfmTestSession = LastfmSession( + username: 'listener', + key: 'session-key', +); + +LastfmScrobble lastfmQueued(int id, {String username = 'listener'}) => + LastfmScrobble( + id: '$id', + username: username, + track: const LastfmTrack( + title: 'Song', + artist: 'Artist', + duration: Duration(minutes: 4), + ), + started: DateTime.utc(2026, 11, 1, 12).add(Duration(minutes: id)), + ); + +class MemoryLastfmStore implements LastfmStore { + LastfmSession? session = lastfmTestSession; + bool enabled = true; + bool nowPlaying = true; + List queue = []; + bool failRead = false, failWrite = false; + int writes = 0; + Completer? sessionGate; + + @override + Future readSession() async => session; + + @override + Future writeSession(LastfmSession? value) async { + await sessionGate?.future; + if (failWrite) throw StateError('Secure storage unavailable'); + session = value; + } + + @override + Future<({bool enabled, bool nowPlaying, List queue})> + read() async { + if (failRead) throw StateError('Storage unavailable'); + return (enabled: enabled, nowPlaying: nowPlaying, queue: List.of(queue)); + } + + @override + Future write({ + required bool enabled, + required bool nowPlaying, + required List queue, + }) async { + if (failWrite) throw StateError('Storage unavailable'); + writes++; + this.enabled = enabled; + this.nowPlaying = nowPlaying; + this.queue = List.of(queue); + } +} + +class FakeLastfmApi extends LastfmApi { + FakeLastfmApi({bool configured = true}) + : super( + credentials: LastfmCredentials( + apiKey: configured ? 'app-key' : '', + apiSecret: configured ? 'app-secret' : '', + ), + ); + + final announcements = >[]; + final batches = >>[]; + final accounts = []; + Object? announceError, batchError, sessionError; + Completer? sessionResult; + Completer? batchGate; + int tokenRequests = 0; + void Function()? onBatch; + + @override + Future requestToken() async { + tokenRequests++; + return 'request-token'; + } + + @override + Future session(String token) async { + if (sessionError case final error?) throw error; + return sessionResult?.future ?? Future.value(lastfmTestSession); + } + + @override + Future nowPlaying( + LastfmSession session, + Map track, + ) async { + announcements.add(Map.of(track)); + if (announceError case final error?) throw error; + } + + @override + Future scrobble( + LastfmSession session, + List> tracks, + ) async { + accounts.add(session.username); + batches.add([for (final track in tracks) Map.of(track)]); + onBatch?.call(); + await batchGate?.future; + if (batchError case final error?) throw error; + } +}