feat(motion): save animated covers as cover.mp4 in album folders

An opt-in Files setting copies a download's animated cover into its
album folder as cover.mp4, so file managers and other players find it.
Only folders that hold one album get it: the folder is planned again
with a marked album name, and flat, artist, playlist and shared Singles
folders are skipped, as is a song kept in a folder other than the
planned one. An existing cover.mp4 is never replaced, for local files,
Android folder access and network storage alike; songs of one album
that finish together write it once.

The player, mini player and album headers now show a cover.mp4 found
beside a local song before the artwork saved for the album. Android
documents are found through a new findSafSibling call and copied into
app storage once per version, since the video player only opens files.
This commit is contained in:
zarzet committed 2026-11-07 16:04:21 +07:00
1 parent bbd4332653
commit efe4df0e1f
23 files changed
+1019 -8

No files matched your search

@@ -123,6 +123,7 @@ class MainActivity: FlutterFragmentActivity() {
"writeSafSidecarLrc",
"writeSafSidecar",
"readSafSidecar",
"findSafSibling",
"downloadCoverToFile",
"extractCoverToFile",
"rewriteSplitArtistTags",
@@ -562,6 +563,7 @@ class MainActivity: FlutterFragmentActivity() {
"writeSafSidecarLrc" -> handleWriteSafSidecarLrc(call, result)
"writeSafSidecar" -> handleWriteSafSidecar(call, result)
"readSafSidecar" -> handleReadSafSidecar(call, result)
"findSafSibling" -> handleFindSafSibling(call, result)
"downloadCoverToFile" -> handleDownloadCoverToFile(call, result)
"extractCoverToFile" -> handleExtractCoverToFile(call, result)
"reEnrichFile" -> handleReEnrichFile(call, result)
@@ -422,6 +422,20 @@ internal suspend fun MainActivity.handleReadSafSidecar(call: MethodCall, result:
result.success(content)
}
internal suspend fun MainActivity.handleFindSafSibling(call: MethodCall, result: MethodChannel.Result) {
val safUri = call.argument<String>("saf_uri") ?: ""
val name = call.argument<String>("name") ?: ""
val sibling = withContext(Dispatchers.IO) {
// A plain file name: never a path into another folder.
if (name.isBlank() || name.contains('/') || name.startsWith('.')) {
null
} else {
findSafSibling(Uri.parse(safUri), name)
}
}
result.success(sibling)
}
internal suspend fun MainActivity.handleGetSafFileModTimes(call: MethodCall, result: MethodChannel.Result) {
val uris = call.argument<String>("uris") ?: "[]"
val response = withContext(Dispatchers.IO) {
@@ -529,6 +529,26 @@ internal fun Context.readSafSidecar(
}
}
/**
* The file named [name] in the folder of a SAF audio document, such as an
* album's "cover.mp4", as its uri, size and modification time, or null when
* the folder has none.
*/
internal fun Context.findSafSibling(audioUri: Uri, name: String): Map<String, Any>? {
return try {
val parent = safParentDir(audioUri) ?: return null
val sibling = findSafChild(this, parent, name)?.takeIf { it.isFile } ?: return null
mapOf(
"uri" to sibling.uri.toString(),
"size" to sibling.length(),
"modified" to sibling.lastModified(),
)
} catch (e: Exception) {
android.util.Log.w("Mornye", "Sibling lookup failed: ${e.message}")
null
}
}
internal fun Context.runPostProcessingSafV2(
coreBackend: CoreBackend,
fileUriStr: String,
+8
View File
@@ -528,6 +528,14 @@
"@downloadSingleFilenameFormatDescription": {
"description": "Subtitle description for single filename format setting"
},
"downloadSaveMotionArtwork": "Save Animated Covers",
"@downloadSaveMotionArtwork": {
"description": "Files setting that copies an album's animated cover video into the album's download folder"
},
"downloadSaveMotionArtworkSubtitle": "Adds the album's animated cover to its folder as cover.mp4, for albums that have their own folder",
"@downloadSaveMotionArtworkSubtitle": {
"description": "Subtitle of the Save Animated Covers switch. Keep 'cover.mp4' as is: it is a file name"
},
"downloadFolderOrganization": "Folder Organization",
"@downloadFolderOrganization": {
"description": "Title of the folder organization picker bottom sheet"
+7
View File
@@ -216,6 +216,9 @@ class AppSettings {
final String lyricsMode;
final bool keepScreenOnLyrics;
final bool motionArtworkEnabled;
/// Copy a download's animated cover into its album folder as `cover.mp4`.
final bool saveMotionArtworkFile;
final bool listeningStatisticsEnabled;
final bool autoConvertDownloads;
// Re-download a Hi-Res request at LOSSLESS when the file measures as fake.
@@ -402,6 +405,7 @@ class AppSettings {
this.lyricsMode = 'embed',
this.keepScreenOnLyrics = true,
this.motionArtworkEnabled = true,
this.saveMotionArtworkFile = false,
this.listeningStatisticsEnabled = true,
this.autoConvertDownloads = false,
this.redownloadFakeHiRes = false,
@@ -563,6 +567,7 @@ class AppSettings {
String? lyricsMode,
bool? keepScreenOnLyrics,
bool? motionArtworkEnabled,
bool? saveMotionArtworkFile,
bool? listeningStatisticsEnabled,
bool? autoConvertDownloads,
bool? redownloadFakeHiRes,
@@ -725,6 +730,8 @@ class AppSettings {
lyricsMode: lyricsMode ?? this.lyricsMode,
keepScreenOnLyrics: keepScreenOnLyrics ?? this.keepScreenOnLyrics,
motionArtworkEnabled: motionArtworkEnabled ?? this.motionArtworkEnabled,
saveMotionArtworkFile:
saveMotionArtworkFile ?? this.saveMotionArtworkFile,
listeningStatisticsEnabled:
listeningStatisticsEnabled ?? this.listeningStatisticsEnabled,
autoConvertDownloads: autoConvertDownloads ?? this.autoConvertDownloads,
+2
View File
@@ -136,6 +136,7 @@ AppSettings _$AppSettingsFromJson(Map<String, dynamic> json) => AppSettings(
lyricsMode: json['lyricsMode'] as String? ?? 'embed',
keepScreenOnLyrics: json['keepScreenOnLyrics'] as bool? ?? true,
motionArtworkEnabled: json['motionArtworkEnabled'] as bool? ?? true,
saveMotionArtworkFile: json['saveMotionArtworkFile'] as bool? ?? false,
listeningStatisticsEnabled:
json['listeningStatisticsEnabled'] as bool? ?? true,
autoConvertDownloads: json['autoConvertDownloads'] as bool? ?? false,
@@ -290,6 +291,7 @@ Map<String, dynamic> _$AppSettingsToJson(
'lyricsMode': instance.lyricsMode,
'keepScreenOnLyrics': instance.keepScreenOnLyrics,
'motionArtworkEnabled': instance.motionArtworkEnabled,
'saveMotionArtworkFile': instance.saveMotionArtworkFile,
'listeningStatisticsEnabled': instance.listeningStatisticsEnabled,
'autoConvertDownloads': instance.autoConvertDownloads,
'redownloadFakeHiRes': instance.redownloadFakeHiRes,
@@ -1000,6 +1000,22 @@ class DownloadQueueNotifier extends Notifier<DownloadQueueState> {
playlistName: playlistName,
);
@visibleForTesting
Future<bool> holdsAlbumFilesFor(
DownloadItem item,
AppSettings settings, {
required String filePath,
String? relativeDir,
String quality = 'LOSSLESS',
}) => _holdsAlbumFiles(
item.track,
item,
settings,
quality,
filePath: filePath,
relativeDir: relativeDir,
);
DownloadItem? _findItemById(String id) {
return state.lookup.byItemId[id];
}
@@ -48,12 +48,22 @@ extension _DownloadQueueFinalization on DownloadQueueNotifier {
info: _log.i,
);
/// Saves the album's animated cover for the player and, when the settings
/// ask, as `cover.mp4` beside [filePath] in the album's own folder: an
/// Android document there needs [treeUri] and [relativeDir]. The folder
/// was planned from [folderTrack], when it differs from [track].
Future<void> _saveDownloadedMotionArtwork(
Ref ref,
DownloadItem item,
Track track,
Map<String, dynamic> result,
) async {
Map<String, dynamic> result, {
required AppSettings settings,
required String quality,
String? filePath,
String? treeUri,
String? relativeDir,
Track? folderTrack,
}) async {
// Store independently of history preferences and the selected UI theme.
// A later switch to Mornye must still work without network access.
try {
@@ -84,6 +94,30 @@ extension _DownloadQueueFinalization on DownloadQueueNotifier {
if (artwork != null && ref.mounted) {
ref.invalidate(playerMotionArtworkProvider(album));
}
if (artwork == null ||
filePath == null ||
!settings.saveMotionArtworkFile ||
!ref.mounted ||
!await _holdsAlbumFiles(
folderTrack ?? track,
item,
settings,
quality,
filePath: filePath,
relativeDir: relativeDir,
) ||
!ref.mounted) {
return;
}
final saved = await ref
.read(motionArtworkFolderProvider)
.save(
File.fromUri(Uri.parse(artwork.source)),
song: filePath,
treeUri: treeUri,
relativeDir: relativeDir,
);
if (saved) _log.i('Animated cover saved to the album folder');
} catch (error) {
_log.w('Optional motion artwork was not saved: ${error.runtimeType}');
}
@@ -1257,7 +1257,17 @@ extension _DownloadQueueNativeWorker on DownloadQueueNotifier {
if (result.nativeFinalized) {
final nativeFinalizedFilePath = filePath;
await _saveDownloadedMotionArtwork(ref, item, item.track, result);
await _saveDownloadedMotionArtwork(
ref,
item,
item.track,
result,
settings: settings,
quality: context.quality,
filePath: nativeFinalizedFilePath,
treeUri: context.storageMode == 'saf' ? context.downloadTreeUri : null,
relativeDir: context.safRelativeDir,
);
await persistBeforePublishingDownloadCompletion(
persist: () async {
if (!settings.saveDownloadHistory) return;
@@ -1521,7 +1531,18 @@ extension _DownloadQueueNativeWorker on DownloadQueueNotifier {
lowerFilePath.endsWith('.ogg');
final completedFilePath = filePath;
await _saveDownloadedMotionArtwork(ref, item, trackToDownload, result);
await _saveDownloadedMotionArtwork(
ref,
item,
trackToDownload,
result,
settings: settings,
quality: context.quality,
filePath: completedFilePath,
treeUri: context.storageMode == 'saf' ? context.downloadTreeUri : null,
relativeDir: context.safRelativeDir,
folderTrack: item.track,
);
final lyricsAvailability = await _resolveFinalLyricsAvailability(
filePath: completedFilePath,
externalLrcWritten: externalLrcWritten,
@@ -453,6 +453,89 @@ extension _DownloadQueuePaths on DownloadQueueNotifier {
};
}
/// The folder, as relative parts, when downloads of [track] go to a folder
/// of their album alone, so files that belong to the whole album can sit
/// beside them. Planned again with a marker for the album name: a folder
/// that holds an album names it in its last part and nowhere else differs.
Future<List<String>?> _albumFolderParts(
Track track,
DownloadItem item,
AppSettings settings,
String quality,
) async {
if (track.albumName.trim().isEmpty) return null;
const marker = 'mornyealbumfolder';
Future<List<String>> folder(Track value) async => _buildRelativeOutputDir(
value,
settings,
customFolderPath: await _resolveCustomFolderPath(
value,
item,
settings,
quality,
),
playlistName: item.playlistName,
).split('/').where((part) => part.isNotEmpty).toList();
final markedTrack = track.copyWith(albumName: marker);
// An album named like "Singles" counts as a single: renaming it must
// not move it out of the shared Singles folder.
if (settings.separateSingles &&
_shouldTreatAsSingleRelease(track) !=
_shouldTreatAsSingleRelease(markedTrack)) {
return null;
}
final planned = await folder(track);
final marked = await folder(markedTrack);
bool named(String part) => part.toLowerCase().contains(marker);
// A playlist folder or a shared Singles folder names no album.
if (marked.isEmpty || planned.length != marked.length) return null;
if (!named(marked.last)) return null;
for (var i = 0; i < marked.length; i++) {
if (!named(marked[i]) && marked[i] != planned[i]) return null;
}
return planned;
}
/// Whether the song of [track] saved at [filePath], or as a document in
/// [relativeDir], sits in a folder of its album alone, and not in one an
/// earlier copy of it was kept in.
Future<bool> _holdsAlbumFiles(
Track track,
DownloadItem item,
AppSettings settings,
String quality, {
required String filePath,
String? relativeDir,
}) async {
final parts = await _albumFolderParts(track, item, settings, quality);
return parts != null && _isInAlbumFolder(filePath, relativeDir, parts);
}
bool _isInAlbumFolder(
String filePath,
String? relativeDir,
List<String> parts,
) {
final List<String> folder;
if (isContentUri(filePath)) {
folder = (relativeDir ?? '').split('/');
} else if (filePath.startsWith('network://')) {
final segments = Uri.tryParse(filePath)?.pathSegments ?? const [];
folder = segments.isEmpty
? const []
: segments.sublist(0, segments.length - 1);
} else {
folder = p.split(p.dirname(filePath));
}
final named = folder.where((part) => part.isNotEmpty).toList();
if (named.length < parts.length) return false;
final tail = named.sublist(named.length - parts.length);
for (var i = 0; i < parts.length; i++) {
if (tail[i] != parts[i]) return false;
}
return true;
}
String _joinRelativePath(String prefix, String suffix) {
if (prefix.isEmpty) return suffix;
if (suffix.isEmpty) return prefix;
@@ -1682,6 +1682,11 @@ class _DownloadRun {
item,
trackToDownload,
result,
settings: settings,
quality: quality,
filePath: historyFilePath,
treeUri: effectiveSafMode ? settings.downloadTreeUri : null,
relativeDir: effectiveSafMode ? effectiveOutputDir : null,
);
onStageCompleted?.call('optional motion artwork');
await persistBeforePublishingDownloadCompletion(
@@ -1,5 +1,6 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mornye/providers/settings_provider.dart';
import 'package:mornye/services/motion_artwork_folder.dart';
import 'package:mornye/services/motion_artwork_store.dart';
import 'package:mornye/utils/logger.dart';
import 'package:mornye/utils/string_utils.dart';
@@ -8,6 +9,12 @@ typedef PlayerArtworkAlbum = ({String album, String artist});
final motionArtworkStoreProvider = Provider((ref) => MotionArtworkStore());
final motionArtworkFolderProvider = Provider((ref) => MotionArtworkFolder());
/// An album and the song, or one of its songs, whose folder may hold the
/// album's `cover.mp4`.
typedef PlayerArtworkSong = ({String album, String artist, String source});
/// Player and local album pages read artwork saved by downloads or re-enrich.
/// Opening either must never search extensions or download more artwork.
final playerMotionArtworkProvider = FutureProvider.autoDispose
@@ -21,6 +28,26 @@ final playerMotionArtworkProvider = FutureProvider.autoDispose
return ref.watch(motionArtworkStoreProvider).find(album);
});
/// The artwork for a song: a `cover.mp4` in its folder first, since that
/// one belongs to exactly this album and is the user's own file, then the
/// artwork saved for the album.
final songMotionArtworkProvider = FutureProvider.autoDispose
.family<MotionArtwork?, PlayerArtworkSong>((ref, song) async {
if (!ref.watch(settingsProvider.select((s) => s.motionArtworkEnabled))) {
return null;
}
final (beside, saved) = await (
ref.watch(motionArtworkFolderProvider).find(song.source),
ref.watch(
playerMotionArtworkProvider((
album: song.album,
artist: song.artist,
)).future,
),
).wait;
return beside ?? saved;
});
/// Optional video is kept outside audio tags, after the metadata write succeeds.
Future<void> saveReEnrichedMotionArtwork(
ProviderContainer container, {
+3
View File
@@ -778,6 +778,9 @@ class SettingsNotifier extends Notifier<AppSettings> {
void setMotionArtworkEnabled(bool enabled) =>
_commit(state.copyWith(motionArtworkEnabled: enabled));
void setSaveMotionArtworkFile(bool enabled) =>
_commit(state.copyWith(saveMotionArtworkFile: enabled));
void setListeningStatisticsEnabled(bool enabled) =>
_commit(state.copyWith(listeningStatisticsEnabled: enabled));
+2 -1
View File
@@ -377,11 +377,12 @@ class _DownloadedAlbumScreenState extends ConsumerState<DownloadedAlbumScreen>
final motion = context.isMornye && !MediaQuery.disableAnimationsOf(context)
? ref
.watch(
playerMotionArtworkProvider((
songMotionArtworkProvider((
album: widget.albumName,
artist: tracks.isEmpty
? widget.artistName
: tracks.first.artistName,
source: tracks.firstOrNull?.filePath ?? '',
)),
)
.value
+2 -1
View File
@@ -368,11 +368,12 @@ class _LocalAlbumScreenState extends ConsumerState<LocalAlbumScreen>
final motion = context.isMornye && !MediaQuery.disableAnimationsOf(context)
? ref
.watch(
playerMotionArtworkProvider((
songMotionArtworkProvider((
album: widget.albumName,
artist:
_sortedTracksCache.firstOrNull?.artistName ??
widget.artistName,
source: _sortedTracksCache.firstOrNull?.filePath ?? '',
)),
)
.value
+2 -1
View File
@@ -353,9 +353,10 @@ class _NowPlayingScreenState extends ConsumerState<NowPlayingScreen> {
ref.watch(settingsProvider.select((s) => s.motionArtworkEnabled)) &&
!MediaQuery.disableAnimationsOf(context)
? ref.watch(
playerMotionArtworkProvider((
songMotionArtworkProvider((
album: mediaItem.album ?? '',
artist: mediaItem.artist ?? '',
source: source,
)),
)
: null;
@@ -154,7 +154,9 @@ class _CacheManagementPageState extends ConsumerState<CacheManagementPage> {
}
Future<void> _clearMotionArtwork() async {
// Copies of folder covers live in the same directory.
await ref.read(motionArtworkStoreProvider).clear();
ref.read(motionArtworkFolderProvider).forget();
if (mounted) ref.invalidate(playerMotionArtworkProvider);
}
@@ -220,6 +220,15 @@ class _FilesSettingsPageState extends ConsumerState<FilesSettingsPage> {
description:
context.l10n.downloadSingleFilenameFormatDescription,
),
),
SettingsSwitchItem(
icon: Icons.motion_photos_on_outlined,
title: context.l10n.downloadSaveMotionArtwork,
subtitle: context.l10n.downloadSaveMotionArtworkSubtitle,
value: settings.saveMotionArtworkFile,
onChanged: ref
.read(settingsProvider.notifier)
.setSaveMotionArtworkFile,
showDivider: false,
),
],
+289
View File
@@ -0,0 +1,289 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:crypto/crypto.dart';
import 'package:path/path.dart' as p;
import 'package:mornye/services/motion_artwork_store.dart';
import 'package:mornye/services/network_storage_service.dart';
import 'package:mornye/services/platform_bridge.dart';
import 'package:mornye/utils/file_access.dart';
import 'package:mornye/utils/logger.dart';
/// The name an album's animated cover has in the album's folder.
const motionArtworkFileName = 'cover.mp4';
const _maxBytes = 64 << 20;
typedef MotionArtworkDocument = ({String uri, int size, int modified});
/// An album's animated cover kept as `cover.mp4` in the album's own folder,
/// where file managers and other players find it. Downloads write it there
/// when the settings ask; the player shows one it finds beside a song.
class MotionArtworkFolder {
MotionArtworkFolder({
Future<Directory> Function()? directory,
Future<MotionArtworkDocument?> Function(String song, String name)? sibling,
Future<String?> Function(String uri)? copyDocument,
Future<bool> Function(
String treeUri,
String relativeDir,
String name,
String path,
)?
createDocument,
Future<bool> Function(String target, File file)? upload,
bool? documents,
}) : _directory = directory ?? MotionArtworkStore.defaultDirectory,
_sibling = sibling ?? PlatformBridge.findSafSibling,
_copyDocument = copyDocument ?? PlatformBridge.copyContentUriToTemp,
_createDocument = createDocument ?? _createSafDocument,
_upload = upload ?? _uploadToNetwork,
_documents = documents ?? Platform.isAndroid;
final Future<Directory> Function() _directory;
final Future<MotionArtworkDocument?> Function(String song, String name)
_sibling;
final Future<String?> Function(String uri) _copyDocument;
final Future<bool> Function(
String treeUri,
String relativeDir,
String name,
String path,
)
_createDocument;
final Future<bool> Function(String target, File file) _upload;
final bool _documents;
final _saving = <String, Future<bool>>{};
final _done = <String>{};
final _copying = <String, Future<MotionArtwork?>>{};
/// Android document lookups by song, so moving between songs does not ask
/// the provider again; a cover added later shows within minutes.
final _found = <String, (DateTime, Future<MotionArtwork?>)>{};
static const _foundFor = Duration(minutes: 5);
static final _log = AppLogger('MotionArtworkFolder');
/// Forgets document lookups, after their copies were cleared.
void forget() => _found.clear();
/// Saves [video] as the `cover.mp4` of the folder holding [song]: a local
/// path, an Android document in [treeUri]/[relativeDir], or a network
/// song. A cover already there stays. True when one was written.
Future<bool> save(
File video, {
required String song,
String? treeUri,
String? relativeDir,
}) {
final String folder;
final Future<bool> Function() write;
if (song.startsWith('network://')) {
final uri = Uri.tryParse(song);
if (uri == null || uri.host.isEmpty) return Future.value(false);
final parent = p.posix.dirname(uri.pathSegments.join('/'));
folder = NetworkStorageService.source(
uri.host,
parent == '.'
? motionArtworkFileName
: '$parent/$motionArtworkFileName',
);
write = () => _upload(folder, video);
} else if (isContentUri(song)) {
if (treeUri == null || treeUri.isEmpty || relativeDir == null) {
return Future.value(false);
}
folder = '$treeUri\n$relativeDir';
write = () => _createDocument(
treeUri,
relativeDir,
motionArtworkFileName,
video.path,
);
} else {
final path = _localPath(song);
if (path == null) return Future.value(false);
folder = p.dirname(path);
write = () => _copyLocal(video, folder);
}
// Songs of one album finish together: the first writes, the rest wait
// for it, and later ones in this session do not look again.
if (_done.contains(folder)) return Future.value(false);
final pending = _saving[folder];
if (pending != null) return pending.then((_) => false);
final saving = () async {
try {
if (!await video.exists() || await video.length() == 0) return false;
final written = await write();
if (_done.length >= 256) _done.clear();
_done.add(folder);
return written;
} catch (error) {
_log.w('Animated cover was not saved to the folder: $error');
return false;
}
}();
_saving[folder] = saving;
return saving.whenComplete(() => _saving.remove(folder));
}
Future<bool> _copyLocal(File video, String folder) async {
final target = File(p.join(folder, motionArtworkFileName));
if (await target.exists()) return false;
final staged = File('${target.path}.partial');
try {
await video.copy(staged.path);
if (await target.exists()) return false;
await staged.rename(target.path);
return true;
} finally {
if (await staged.exists()) await deleteFileQuietly(staged);
}
}
/// The `cover.mp4` in [song]'s folder as a local file the player can show,
/// or null when there is none. Android documents are copied into the app
/// once, since the video player only opens files.
Future<MotionArtwork?> find(String song) async {
if (song.isEmpty || song.startsWith('network://')) return null;
if (isContentUri(song)) {
if (!_documents) return null;
final now = DateTime.now();
final found = _found[song];
if (found != null && now.difference(found.$1) < _foundFor) {
return found.$2;
}
if (_found.length >= 64) _found.clear();
final lookup = _findDocument(song);
_found[song] = (now, lookup);
return lookup;
}
final path = _localPath(song);
if (path == null) return null;
try {
final file = File(p.join(p.dirname(path), motionArtworkFileName));
if (!await file.exists()) return null;
final length = await file.length();
if (length == 0 || length > _maxBytes) return null;
return MotionArtwork(file.uri.toString());
} catch (_) {
return null;
}
}
Future<MotionArtwork?> _findDocument(String song) async {
try {
final document = await _sibling(song, motionArtworkFileName);
if (document == null || document.size <= 0 || document.size > _maxBytes) {
return null;
}
// Songs of one album share a cover: copy it once.
final pending = _copying[document.uri];
if (pending != null) return await pending;
final copying = _copyIn(document);
_copying[document.uri] = copying;
try {
return await copying;
} finally {
_copying.remove(document.uri);
}
} catch (error) {
_log.w('Could not read the folder animated cover: $error');
return null;
}
}
Future<MotionArtwork?> _copyIn(MotionArtworkDocument document) async {
File? staged;
try {
final root = Directory(p.join((await _directory()).path, 'folder'));
final key = sha256.convert(utf8.encode(document.uri)).toString();
final file = File(p.join(root.path, '$key.mp4'));
final info = File(p.join(root.path, '$key.json'));
final stamp = jsonEncode({
'size': document.size,
'modified': document.modified,
});
if (await file.exists() &&
await info.exists() &&
await info.readAsString() == stamp) {
return MotionArtwork(file.uri.toString());
}
final copied = await _copyDocument(document.uri);
if (copied == null) return null;
await root.create(recursive: true);
staged = File(p.join(root.path, '$key.partial.mp4'));
final source = File(copied);
try {
await source.rename(staged.path);
} on FileSystemException {
await source.copy(staged.path);
await deleteFileQuietly(source);
}
if (await staged.length() != document.size) return null;
await staged.rename(file.path);
await info.writeAsString(stamp, flush: true);
return MotionArtwork(file.uri.toString());
} catch (error) {
_log.w('Could not read the folder animated cover: $error');
return null;
} finally {
if (staged != null && await staged.exists()) {
await deleteFileQuietly(staged);
}
}
}
static String? _localPath(String song) {
if (song.isEmpty ||
isContentUri(song) ||
const {'http', 'https'}.contains(Uri.tryParse(song)?.scheme)) {
return null;
}
final uri = Uri.tryParse(song);
final path = uri?.scheme == 'file' ? uri!.toFilePath() : song;
final real = isCueVirtualPath(path) ? stripCueTrackSuffix(path) : path;
return p.isAbsolute(real) ? real : null;
}
static Future<bool> _createSafDocument(
String treeUri,
String relativeDir,
String name,
String path,
) async {
final result = await PlatformBridge.createSafFileIfAbsentFromPath(
treeUri: treeUri,
relativeDir: relativeDir,
fileName: name,
mimeType: 'video/mp4',
srcPath: path,
);
final uri = (result['uri'] as String? ?? '').trim();
return uri.isNotEmpty && result['already_exists'] != true;
}
static Future<bool> _uploadToNetwork(String target, File file) async {
final storage = NetworkStorageService.instance;
final uri = Uri.parse(target);
final path = networkPath(uri.pathSegments.join('/'));
final slash = path.lastIndexOf('/');
final parent = slash < 0 ? '' : path.substring(0, slash + 1);
// Looking by name first: an upload over an existing file would download
// it to compare, and a different one is the user's to keep.
final entries = await storage.list(
await storage.connection(uri.host),
parent,
);
if (entries.any((e) => e.name.toLowerCase() == motionArtworkFileName)) {
return false;
}
await storage.publishUpload(
target,
file,
'motion-cover:$target',
checkpoint: () {},
progress: (_, _) {},
);
return true;
}
}
+17
View File
@@ -1702,6 +1702,23 @@ class PlatformBridge {
'extension': extension,
});
/// The file named [name] in the folder of the SAF document [safUri], or
/// null when the folder has none.
static Future<({String uri, int size, int modified})?> findSafSibling(
String safUri,
String name,
) async {
final result = await _channel.invokeMethod<Map<Object?, Object?>>(
'findSafSibling',
{'saf_uri': safUri, 'name': name},
);
final uri = result?['uri'];
final size = result?['size'];
final modified = result?['modified'];
if (uri is! String || size is! int || modified is! int) return null;
return (uri: uri, size: size, modified: modified);
}
static Future<void> startDownloadService({
String trackName = '',
String artistName = '',
+6
View File
@@ -665,6 +665,12 @@ class SettingsSearchCatalog {
title: l10n.downloadSingleFilenameFormat,
keywords: const ['single naming', 'file template'],
),
SettingsSearchEntry(
icon: Icons.motion_photos_on_outlined,
title: l10n.downloadSaveMotionArtwork,
subtitle: l10n.downloadSaveMotionArtworkSubtitle,
keywords: const ['cover.mp4', 'motion cover', 'video', 'animation'],
),
SettingsSearchEntry(
icon: Icons.library_music_outlined,
title: l10n.downloadSeparateSinglesFolder,
+2 -1
View File
@@ -231,9 +231,10 @@ class _MiniPlayerBodyState extends ConsumerState<_MiniPlayerBody> {
!MediaQuery.disableAnimationsOf(context)) {
final artwork = ref
.watch(
playerMotionArtworkProvider((
songMotionArtworkProvider((
album: mediaItem.album ?? '',
artist: mediaItem.artist ?? '',
source: mediaItem.extras?['source']?.toString() ?? '',
)),
)
.value;
+442
View File
@@ -0,0 +1,442 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mornye/models/download_item.dart';
import 'package:mornye/models/settings.dart';
import 'package:mornye/models/track.dart';
import 'package:mornye/providers/download_queue_provider.dart';
import 'package:mornye/providers/player_motion_artwork_provider.dart';
import 'package:mornye/providers/settings_provider.dart';
import 'package:mornye/services/motion_artwork_folder.dart';
import 'package:mornye/services/motion_artwork_store.dart';
import 'package:mornye/services/network_storage_service.dart';
import 'package:path/path.dart' as p;
import 'package:shared_preferences/shared_preferences.dart';
const _album = Track(
id: 'album',
name: 'Song',
artistName: 'Artist',
albumName: 'Album',
duration: 180,
albumType: 'album',
totalTracks: 10,
);
const _single = Track(
id: 'single',
name: 'Song',
artistName: 'Artist',
albumName: 'Song',
duration: 180,
albumType: 'single',
totalTracks: 1,
);
DownloadItem _item(Track track, {String? playlist}) => DownloadItem(
id: track.id,
track: track,
service: 'example',
playlistName: playlist,
createdAt: DateTime(2026),
);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('album folder rule', () {
final queue = DownloadQueueNotifier();
Future<bool> holds(
AppSettings settings, {
Track track = _album,
String? playlist,
String? path,
}) {
final planned = queue.relativeOutputDirFor(
track,
settings,
playlistName: playlist,
);
return queue.holdsAlbumFilesFor(
_item(track, playlist: playlist),
settings,
filePath: path ?? p.join('/music', planned, 'Song.flac'),
);
}
test('album folders hold album files', () async {
for (final structure in ['artist_album', 'album_only', 'year_album']) {
expect(
await holds(
AppSettings(
folderOrganization: 'album',
albumFolderStructure: structure,
separateSingles: false,
),
),
isTrue,
reason: structure,
);
}
expect(
await holds(
const AppSettings(
folderOrganization: 'artist_album',
separateSingles: false,
),
),
isTrue,
);
// Albums kept apart from singles still get a folder each.
expect(
await holds(
const AppSettings(
folderOrganization: 'none',
separateSingles: true,
albumFolderStructure: 'artist_album_singles',
),
),
isTrue,
);
});
test('shared folders never get an album file', () async {
for (final organization in ['none', 'artist']) {
expect(
await holds(
AppSettings(
folderOrganization: organization,
separateSingles: false,
),
),
isFalse,
reason: organization,
);
}
expect(
await holds(
const AppSettings(
folderOrganization: 'playlist',
separateSingles: false,
),
playlist: 'Road Trip',
),
isFalse,
);
// Every single shares one Singles folder.
expect(
await holds(
const AppSettings(
folderOrganization: 'none',
separateSingles: true,
albumFolderStructure: 'artist_album_singles',
),
track: _single,
),
isFalse,
);
// A release named like the Singles folder is still a single there.
expect(
await holds(
const AppSettings(
folderOrganization: 'none',
separateSingles: true,
albumFolderStructure: 'artist_album_singles',
),
track: Track(
id: 'named',
name: 'Song',
artistName: 'Artist',
albumName: 'Singles',
duration: 180,
totalTracks: 2,
),
),
isFalse,
);
expect(
await queue.holdsAlbumFilesFor(
_item(_album.copyWith(albumName: ' ')),
const AppSettings(
folderOrganization: 'album',
separateSingles: false,
),
filePath: '/music/Artist/Song.flac',
),
isFalse,
);
});
test('the song must be in the planned folder', () async {
const settings = AppSettings(
folderOrganization: 'album',
albumFolderStructure: 'artist_album',
separateSingles: false,
);
final planned = queue.relativeOutputDirFor(_album, settings);
// An earlier copy kept in an older flat layout.
expect(await holds(settings, path: '/music/Song.flac'), isFalse);
expect(
await queue.holdsAlbumFilesFor(
_item(_album),
settings,
filePath: 'content://tree/document/song',
relativeDir: planned,
),
isTrue,
);
expect(
await queue.holdsAlbumFilesFor(
_item(_album),
settings,
filePath: 'content://tree/document/song',
relativeDir: 'Other',
),
isFalse,
);
expect(
await queue.holdsAlbumFilesFor(
_item(_album),
settings,
filePath: NetworkStorageService.source(
'nas',
'Music/$planned/Song.flac',
),
),
isTrue,
);
});
test('custom folders hold an album when its name ends them', () async {
const backend = MethodChannel('com.zarz.mornye/backend');
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
messenger.setMockMethodCallHandler(backend, (call) async {
if (call.method != 'buildFilename') return null;
final args = call.arguments as Map;
final metadata = jsonDecode(args['metadata'] as String) as Map;
return (args['template'] as String)
.replaceAll('{album}', '${metadata['album']}')
.replaceAll('{artist}', '${metadata['artist']}');
});
addTearDown(() => messenger.setMockMethodCallHandler(backend, null));
Future<bool> custom(String template) async {
final settings = AppSettings(
folderOrganization: 'custom',
folderPathTemplate: template,
separateSingles: false,
);
final item = _item(_album);
final folder = template
.replaceAll('{album}', 'Album')
.replaceAll('{artist}', 'Artist');
return queue.holdsAlbumFilesFor(
item,
settings,
filePath: '/music/$folder/Song.flac',
);
}
expect(await custom('{artist}/{album}'), isTrue);
expect(await custom('{album}/{artist}'), isFalse);
expect(await custom('{artist}'), isFalse);
});
});
group('MotionArtworkFolder', () {
late Directory root;
late File video;
setUp(() async {
root = await Directory.systemTemp.createTemp('motion-folder-');
video = File(p.join(root.path, 'stored.mp4'))
..writeAsBytesSync([1, 2, 3]);
});
tearDown(() => root.delete(recursive: true));
test('writes cover.mp4 beside a local song once', () async {
final album = Directory(p.join(root.path, 'Artist', 'Album'))
..createSync(recursive: true);
final folder = MotionArtworkFolder(directory: () async => root);
final saves = await Future.wait([
folder.save(video, song: p.join(album.path, '01.flac')),
folder.save(video, song: p.join(album.path, '02.flac')),
]);
expect(saves.where((saved) => saved), hasLength(1));
final cover = File(p.join(album.path, motionArtworkFileName));
expect(cover.readAsBytesSync(), [1, 2, 3]);
expect(album.listSync().map((e) => p.basename(e.path)), [
motionArtworkFileName,
]);
expect(
await folder.save(video, song: p.join(album.path, '03.flac')),
isFalse,
);
});
test('keeps a cover the user already has', () async {
final album = Directory(p.join(root.path, 'Album'))..createSync();
final cover = File(p.join(album.path, motionArtworkFileName))
..writeAsBytesSync([9]);
final folder = MotionArtworkFolder(directory: () async => root);
expect(
await folder.save(video, song: p.join(album.path, '01.flac')),
isFalse,
);
expect(cover.readAsBytesSync(), [9]);
});
test('documents and network songs go through their storage', () async {
final created = <String>[];
final uploads = <String>[];
final folder = MotionArtworkFolder(
directory: () async => root,
createDocument: (treeUri, relativeDir, name, path) async {
created.add('$treeUri|$relativeDir|$name|${p.basename(path)}');
return true;
},
upload: (target, file) async {
uploads.add(target);
return true;
},
);
expect(
await folder.save(video, song: 'content://tree/document/song'),
isFalse,
);
expect(
await folder.save(
video,
song: 'content://tree/document/song',
treeUri: 'content://tree',
relativeDir: 'Artist/Album',
),
isTrue,
);
expect(created, ['content://tree|Artist/Album|cover.mp4|stored.mp4']);
final song = NetworkStorageService.source('nas', 'Music/Album/01.flac');
expect(await folder.save(video, song: song), isTrue);
expect(uploads, [
NetworkStorageService.source('nas', 'Music/Album/cover.mp4'),
]);
});
test('finds cover.mp4 beside a local song', () async {
final album = Directory(p.join(root.path, 'Album'))..createSync();
final song = p.join(album.path, '01.flac');
final folder = MotionArtworkFolder(directory: () async => root);
expect(await folder.find(song), isNull);
final cover = File(p.join(album.path, motionArtworkFileName))
..writeAsBytesSync([4, 5]);
expect((await folder.find(song))?.source, cover.uri.toString());
expect(
(await folder.find(Uri.file(song).toString()))?.source,
cover.uri.toString(),
);
expect(
await folder.find(NetworkStorageService.source('nas', 'a/b.flac')),
isNull,
);
});
test('copies a document cover in once per version', () async {
var modified = 1;
var copies = 0;
final folder = MotionArtworkFolder(
directory: () async => root,
documents: true,
sibling: (song, name) async {
expect(name, motionArtworkFileName);
return (
uri: 'content://tree/document/cover',
size: 2,
modified: modified,
);
},
copyDocument: (uri) async {
copies++;
final temp = File(p.join(root.path, 'temp-$copies.mp4'));
await temp.writeAsBytes([7, copies]);
return temp.path;
},
);
final first = await Future.wait([
folder.find('content://tree/document/song-1'),
folder.find('content://tree/document/song-2'),
]);
expect(copies, 1);
expect(first[0]?.source, first[1]?.source);
final copy = File.fromUri(Uri.parse(first[0]!.source));
expect(p.isWithin(root.path, copy.path), isTrue);
expect(copy.readAsBytesSync(), [7, 1]);
// Another song of the album reuses the copy.
await folder.find('content://tree/document/song-3');
expect(copies, 1);
// A replaced cover is copied again once lookups expire.
modified = 2;
folder.forget();
await folder.find('content://tree/document/song-1');
expect(copies, 2);
expect(copy.readAsBytesSync(), [7, 2]);
});
test('documents are not read off Android', () async {
var asked = false;
final folder = MotionArtworkFolder(
directory: () async => root,
documents: false,
sibling: (_, _) async {
asked = true;
return null;
},
);
expect(await folder.find('content://tree/document/song'), isNull);
expect(asked, isFalse);
});
});
group('songMotionArtworkProvider', () {
setUp(() => SharedPreferences.setMockInitialValues({}));
test('prefers the folder cover over the saved one', () async {
final root = await Directory.systemTemp.createTemp('motion-song-');
addTearDown(() => root.delete(recursive: true));
final album = Directory(p.join(root.path, 'Album'))..createSync();
final song = p.join(album.path, '01.flac');
const saved = MotionArtwork('file:///saved.mp4', aspectRatio: 1);
final container = ProviderContainer(
overrides: [
motionArtworkFolderProvider.overrideWithValue(
MotionArtworkFolder(directory: () async => root),
),
playerMotionArtworkProvider.overrideWith((ref, album) async => saved),
],
);
addTearDown(container.dispose);
Future<MotionArtwork?> read(String source) => container.read(
songMotionArtworkProvider((
album: 'Album',
artist: 'Artist',
source: source,
)).future,
);
expect((await read(song))?.source, saved.source);
final cover = File(p.join(album.path, motionArtworkFileName))
..writeAsBytesSync([1]);
container.invalidate(songMotionArtworkProvider);
expect((await read(song))?.source, cover.uri.toString());
expect((await read(''))?.source, saved.source);
container.read(settingsProvider.notifier).setMotionArtworkEnabled(false);
expect(await read(song), isNull);
});
});
}