fix(downloads): preserve artwork in playlist downloads

Recover missing track artwork from the matching source album. Keep temporary covers alive while embedding operations still use them, even after cache eviction or queue cleanup.

Add regressions for mixed-playlist eviction, concurrent writers and source-album artwork recovery.

Validation: 99 Flutter tests passed, scoped analyzer clean, formatter and git diff checks passed.
This commit is contained in:
zarzet committed 2026-11-01 14:24:35 +07:00
1 parent b12f0399bd
commit 6407abedbf
4 files changed
+195 -12

No files matched your search

+11 -3
View File
@@ -5,7 +5,7 @@ import 'package:mornye/utils/string_utils.dart';
final _log = AppLogger('DownloadAlbumMetadata');
/// Resolve the release credit independently of which tracks were selected.
/// Resolve release credits and missing artwork independently of track selection.
/// The bridge caches album responses and coalesces concurrent album lookups.
Future<Track> resolveDownloadAlbumArtist(
Track track,
@@ -32,9 +32,17 @@ Future<Track> resolveDownloadAlbumArtist(
if (value is String) artist = normalizeOptionalString(value);
if (artist != null) break;
}
return artist == null || artist == track.albumArtist
String? cover;
if (normalizeCoverReference(track.coverUrl) == null) {
for (final key in ['cover_url', 'images']) {
final value = info[key];
if (value is String) cover = normalizeCoverReference(value);
if (cover != null) break;
}
}
return (artist == null || artist == track.albumArtist) && cover == null
? track
: track.copyWith(albumArtist: artist);
: track.copyWith(albumArtist: artist, coverUrl: cover);
} catch (error) {
_log.w('Album credit lookup failed; keeping track metadata: $error');
return track;
+39 -9
View File
@@ -17,11 +17,20 @@ import 'package:mornye/utils/logger.dart';
import 'package:mornye/utils/lyrics_metadata_helper.dart';
import 'package:mornye/utils/string_utils.dart';
class _DownloadCover {
_DownloadCover(this.path);
final Future<String?> path;
int users = 0;
bool evicted = false;
bool cleanupStarted = false;
}
/// Embeds tags into a local working file; the queue owns publication and state.
class DownloadMetadataEmbedding {
static final _log = AppLogger('DownloadEmbedding');
static const _coverCacheMax = 8;
final Map<String, Future<String?>> _coverCache = {};
final Map<String, _DownloadCover> _coverCache = {};
final void Function(Track, String, ReplayGainResult) onReplayGain;
final Future<String?> Function(String, int) _loadCover;
final Future<String> Function(Track) _loadLyrics;
@@ -114,9 +123,9 @@ class DownloadMetadataEmbedding {
);
// Start artwork before fetching lyrics so both network round trips overlap.
final coverUrl = normalizeRemoteHttpUrl(track.coverUrl);
final coverFuture = coverUrl == null || coverUrl.isEmpty
final cover = coverUrl == null || coverUrl.isEmpty
? null
: _sharedCover(coverUrl, settings.embeddedCoverMaxDimension);
: _acquireCover(coverUrl, settings.embeddedCoverMaxDimension);
String? lrcContent;
try {
final formattedFields = formatDownloadTagFields(
@@ -182,7 +191,7 @@ class DownloadMetadataEmbedding {
_log.w('Failed to scan ReplayGain for $format: $error');
}
}
final coverPath = coverFuture == null ? null : await coverFuture;
final coverPath = await cover?.path;
final validCover = coverPath != null && await File(coverPath).exists()
? coverPath
: null;
@@ -290,6 +299,11 @@ class DownloadMetadataEmbedding {
}
} catch (error) {
_log.e('Failed to embed metadata to $format: $error');
} finally {
if (cover != null) {
cover.users--;
_cleanUpCover(cover);
}
}
// The cache owns artwork until eviction or queue drain, allowing reuse.
return lrcContent;
@@ -440,27 +454,32 @@ class DownloadMetadataEmbedding {
),
};
Future<String?> _sharedCover(String url, int maxDimension) {
_DownloadCover _acquireCover(String url, int maxDimension) {
final key = '$maxDimension\u0000$url';
final existing = _coverCache.remove(key);
if (existing != null) {
_coverCache[key] = existing;
existing.users++;
return existing;
}
late final _DownloadCover cover;
final fetch = Future<String?>.sync(() => _loadCover(url, maxDimension))
.catchError((Object error) {
_log.w('Failed to load cover for embedding: $error');
return null;
})
.then((path) {
if (path == null) _coverCache.remove(key);
if (path == null && identical(_coverCache[key], cover)) {
_evictCover(key);
}
return path;
});
_coverCache[key] = fetch;
cover = _DownloadCover(fetch)..users = 1;
_coverCache[key] = cover;
while (_coverCache.length > _coverCacheMax) {
_evictCover(_coverCache.keys.first);
}
return fetch;
return cover;
}
static Future<String?> _downloadCover(String url, int maxDimension) async {
@@ -488,7 +507,18 @@ class DownloadMetadataEmbedding {
}
void _evictCover(String key) {
_coverCache.remove(key)?.then((path) {
final cover = _coverCache.remove(key);
if (cover == null) return;
cover.evicted = true;
_cleanUpCover(cover);
}
void _cleanUpCover(_DownloadCover cover) {
// An evicted cover can still be in use by slow lyrics, ReplayGain or a
// metadata writer. Keep the file until every embedding operation finishes.
if (!cover.evicted || cover.users > 0 || cover.cleanupStarted) return;
cover.cleanupStarted = true;
cover.path.then((path) {
if (path != null) File(path).delete().catchError((_) => File(path));
});
}
+55
View File
@@ -21,6 +21,61 @@ void main() {
albumArtist: 'Artist, Guest',
);
test(
'playlist tracks recover missing artwork from their own album',
() async {
final prepared = await resolveDownloadAlbumArtist(
solo,
'example-provider',
loadMetadata: (_, _, id) async => {
'album_info': {
'id': id,
'artists': solo.albumArtist,
'images': 'https://example.test/albums/release-1.jpg',
},
},
);
expect(prepared.coverUrl, 'https://example.test/albums/release-1.jpg');
expect(prepared.id, solo.id);
expect(prepared.albumName, solo.albumName);
expect(prepared.artistName, solo.artistName);
final embedded = buildTrackForMetadataEmbedding(
prepared,
{},
prepared.albumArtist,
);
expect(embedded.coverUrl, prepared.coverUrl);
},
);
test('album artwork recovery preserves an existing track cover', () async {
final selected = solo.copyWith(
coverUrl: 'https://example.test/selected.jpg',
);
final prepared = await resolveDownloadAlbumArtist(
selected,
'example-provider',
loadMetadata: (_, _, id) async => {
'album_info': {'id': id, 'cover_url': 'https://example.test/album.jpg'},
},
);
expect(prepared, same(selected));
});
test('a different release never supplies playlist track artwork', () async {
final prepared = await resolveDownloadAlbumArtist(
solo,
'example-provider',
loadMetadata: (_, _, _) async => {
'album_info': {
'id': 'other',
'images': 'https://example.test/other.jpg',
},
},
);
expect(prepared, same(solo));
});
test('separate downloads use the same album credit as a batch', () async {
Future<Map<String, dynamic>> metadata(
String provider,
@@ -521,6 +521,96 @@ void main() {
},
);
test(
'mixed playlist artwork survives eviction while lyrics are pending',
() async {
final lyricsStarted = Completer<void>();
final lyricsReady = Completer<String>();
final paths = <String, String>{};
final harness = EmbeddingHarness(
loadCover: (url, _) async {
final path = '${directory.path}/playlist-cover-${paths.length}.jpg';
paths[url] = path;
await File(path).writeAsBytes([1, 2, 3]);
return path;
},
loadLyrics: (_) {
lyricsStarted.complete();
return lyricsReady.future;
},
);
final first = harness.service.embed(
'${directory.path}/slow.flac',
track.copyWith(coverUrl: 'https://example.test/cover-0'),
settings: const AppSettings(),
extensionState: const ExtensionState(),
format: 'flac',
);
await lyricsStarted.future;
for (var index = 1; index < 12; index++) {
await harness.service.embed(
'${directory.path}/song-$index.flac',
track.copyWith(coverUrl: 'https://example.test/cover-$index'),
settings: const AppSettings(embedLyrics: false),
extensionState: const ExtensionState(),
format: 'flac',
);
}
lyricsReady.complete('[00:01.00]Line');
await first;
expect(
harness.nativeWrites.last['cover_path'],
paths['https://example.test/cover-0'],
);
harness.service.clearCoverCache();
await _expectDeleted(paths.values);
},
);
test('queue cache cleanup waits for every active cover writer', () async {
final cover = await File(
'${directory.path}/shared.jpg',
).writeAsBytes([1, 2, 3]);
final started = Completer<void>();
final gates = {'first': Completer<void>(), 'second': Completer<void>()};
var writers = 0;
var downloads = 0;
final stillPresent = <bool>[];
final service = DownloadMetadataEmbedding(
onReplayGain: (_, _, _) {},
loadCover: (_, _) async {
downloads++;
return cover.path;
},
editMetadata: (path, fields) async {
expect(fields['cover_path'], cover.path);
if (++writers == 2) started.complete();
await gates[path]!.future;
stillPresent.add(await cover.exists());
return {'success': true, 'method': 'rust'};
},
);
Future<String?> embed(String path) => service.embed(
path,
track.copyWith(coverUrl: 'https://example.test/shared.jpg'),
settings: const AppSettings(embedLyrics: false),
extensionState: const ExtensionState(),
format: 'flac',
);
final first = embed('first');
final second = embed('second');
await started.future;
service.clearCoverCache();
gates['first']!.complete();
await first;
expect(await cover.exists(), isTrue);
gates['second']!.complete();
await second;
expect(downloads, 1);
expect(stillPresent, [true, true]);
await _expectDeleted([cover.path]);
});
test(
'failed covers retry and cache dimensions select separate artwork',
() async {