feat(lastfm): add desktop account connection and scrobbling

Authorize Last.fm accounts in the system browser and store sessions in OS secure storage. Add desktop Playback settings for scrobbling and Now Playing, including localized status and recovery controls.

Observe the local full player, measure actual listening time across pause and seek, distinguish repeats and transitions, and persist qualified listens before submitting account-scoped batches. Keep previews and remote Link sessions outside submission.

Validation: 281 Flutter tests passed, analyzer and pinned formatter clean, workflow lint passed, macOS debug build succeeded, and the signed Last.fm API handshake was verified. Build credentials are supplied locally or through Actions secrets.
This commit is contained in:
zarzet committed 2026-11-01 20:50:03 +07:00
1 parent 3f84aeb5bc
commit 652cd1736b
23 files changed
+2234 -10

No files matched your search

+194
View File
@@ -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 = <http.Request>[];
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<LastfmException>()
.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<String, String> 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<LastfmException>()));
});
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('<html>Unavailable</html>', status),
),
);
addTearDown(api.close);
await expectLater(
api.requestToken(),
throwsA(
isA<LastfmException>().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('<html>Proxy unavailable</html>', 403),
),
);
addTearDown(api.close);
await expectLater(api.requestToken(), throwsFormatException);
},
);
}
+179
View File
@@ -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<LastfmTrack> 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);
});
}
+397
View File
@@ -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 = <LastfmService>[];
void serviceTest(
String description,
Future<void> 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<bool> 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 = <int>[];
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<void>();
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<LastfmSession>();
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<void>();
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);
},
);
}
+111
View File
@@ -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 = <Uri>[];
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<SettingsSwitchItem>(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;
}
},
);
}
+56
View File
@@ -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');
},
);
}
+19
View File
@@ -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 {
+114
View File
@@ -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<LastfmScrobble> queue = [];
bool failRead = false, failWrite = false;
int writes = 0;
Completer<void>? sessionGate;
@override
Future<LastfmSession?> readSession() async => session;
@override
Future<void> writeSession(LastfmSession? value) async {
await sessionGate?.future;
if (failWrite) throw StateError('Secure storage unavailable');
session = value;
}
@override
Future<({bool enabled, bool nowPlaying, List<LastfmScrobble> queue})>
read() async {
if (failRead) throw StateError('Storage unavailable');
return (enabled: enabled, nowPlaying: nowPlaying, queue: List.of(queue));
}
@override
Future<void> write({
required bool enabled,
required bool nowPlaying,
required List<LastfmScrobble> 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 = <Map<String, String>>[];
final batches = <List<Map<String, String>>>[];
final accounts = <String>[];
Object? announceError, batchError, sessionError;
Completer<LastfmSession>? sessionResult;
Completer<void>? batchGate;
int tokenRequests = 0;
void Function()? onBatch;
@override
Future<String> requestToken() async {
tokenRequests++;
return 'request-token';
}
@override
Future<LastfmSession> session(String token) async {
if (sessionError case final error?) throw error;
return sessionResult?.future ?? Future.value(lastfmTestSession);
}
@override
Future<void> nowPlaying(
LastfmSession session,
Map<String, String> track,
) async {
announcements.add(Map.of(track));
if (announceError case final error?) throw error;
}
@override
Future<void> scrobble(
LastfmSession session,
List<Map<String, String>> 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;
}
}