nc-photos/lib/use_case/update_dynamic_album_cover.dart

61 lines
2.1 KiB
Dart
Raw Normal View History

2021-07-01 12:27:37 +02:00
import 'package:nc_photos/entity/album.dart';
import 'package:nc_photos/entity/album/cover_provider.dart';
2021-07-05 09:54:01 +02:00
import 'package:nc_photos/entity/album/item.dart';
2021-07-01 12:27:37 +02:00
import 'package:nc_photos/entity/album/provider.dart';
import 'package:nc_photos/entity/file.dart';
import 'package:nc_photos/entity/file_util.dart' as file_util;
import 'package:nc_photos/iterable_extension.dart';
class UpdateDynamicAlbumCover {
/// Update the cover of a dynamic album with unsorted items
///
/// If no updates are needed, return the same object
Album call(Album album, List<AlbumItem> populatedItems) {
if (album.provider is! AlbumDynamicProvider ||
album.coverProvider is! AlbumAutoCoverProvider) {
return album;
} else {
return _updateWithSortedFiles(
album,
populatedItems
.whereType<AlbumFileItem>()
.map((e) => e.file)
.where((element) => file_util.isSupportedFormat(element))
.sorted(compareFileDateTimeDescending));
}
}
/// Update the cover of a dynamic album with pre-sorted files
///
/// The album items are expected to be sorted by
/// [compareFileDateTimeDescending], otherwise please call the unsorted
/// version. If no updates are needed, return the same object
Album updateWithSortedFiles(Album album, List<File> sortedFiles) {
if (album.provider is! AlbumDynamicProvider ||
album.coverProvider is! AlbumAutoCoverProvider) {
return album;
} else {
return _updateWithSortedFiles(album, sortedFiles);
}
}
Album _updateWithSortedFiles(Album album, List<File> sortedFiles) {
2021-07-23 22:05:57 +02:00
try {
final coverFile =
sortedFiles.firstWhere((element) => element.hasPreview ?? false);
2021-07-01 12:27:37 +02:00
// cache the result for later use
if (coverFile.path !=
(album.coverProvider as AlbumAutoCoverProvider).coverFile?.path) {
return album.copyWith(
coverProvider: AlbumAutoCoverProvider(
coverFile: coverFile,
),
);
}
2021-07-23 22:05:57 +02:00
} on StateError catch (_) {
// no files
2021-07-01 12:27:37 +02:00
}
return album;
}
}