2022-06-06 12:02:54 +02:00
|
|
|
import 'package:flutter/foundation.dart';
|
2021-10-06 22:32:36 +02:00
|
|
|
import 'package:idb_shim/idb_client.dart';
|
|
|
|
import 'package:nc_photos/account.dart';
|
|
|
|
import 'package:nc_photos/app_db.dart';
|
2021-12-07 19:42:25 +01:00
|
|
|
import 'package:nc_photos/di_container.dart';
|
2021-10-06 22:32:36 +02:00
|
|
|
import 'package:nc_photos/entity/file.dart';
|
|
|
|
|
|
|
|
class FindFile {
|
2021-12-07 19:42:25 +01:00
|
|
|
FindFile(this._c) : assert(require(_c));
|
|
|
|
|
|
|
|
static bool require(DiContainer c) => DiContainer.has(c, DiType.appDb);
|
2021-11-01 10:50:13 +01:00
|
|
|
|
2022-01-24 21:32:18 +01:00
|
|
|
/// Find list of files in the DB by [fileIds]
|
|
|
|
///
|
|
|
|
/// If an id is not found, [onFileNotFound] will be called. If
|
|
|
|
/// [onFileNotFound] is null, a [StateError] will be thrown
|
|
|
|
Future<List<File>> call(
|
|
|
|
Account account,
|
|
|
|
List<int> fileIds, {
|
|
|
|
void Function(int fileId)? onFileNotFound,
|
|
|
|
}) async {
|
2022-03-24 10:03:13 +01:00
|
|
|
final dbItems = await _c.appDb.use(
|
|
|
|
(db) => db.transaction(AppDb.file2StoreName, idbModeReadOnly),
|
|
|
|
(transaction) async {
|
|
|
|
final fileStore = transaction.objectStore(AppDb.file2StoreName);
|
2022-06-06 12:02:54 +02:00
|
|
|
return await Future.wait(fileIds.map((id) =>
|
|
|
|
fileStore.getObject(AppDbFile2Entry.toPrimaryKey(account, id))));
|
2022-03-24 10:03:13 +01:00
|
|
|
},
|
|
|
|
);
|
2022-06-06 12:02:54 +02:00
|
|
|
final fileMap = await compute(_covertFileMap, dbItems);
|
2022-01-24 21:32:18 +01:00
|
|
|
final files = <File>[];
|
2022-06-06 12:02:54 +02:00
|
|
|
for (final id in fileIds) {
|
|
|
|
final f = fileMap[id];
|
|
|
|
if (f == null) {
|
2022-01-24 21:32:18 +01:00
|
|
|
if (onFileNotFound == null) {
|
2022-06-06 12:02:54 +02:00
|
|
|
throw StateError("File ID not found: $id");
|
2022-01-24 21:32:18 +01:00
|
|
|
} else {
|
2022-06-06 12:02:54 +02:00
|
|
|
onFileNotFound(id);
|
2022-01-24 21:32:18 +01:00
|
|
|
}
|
|
|
|
} else {
|
2022-06-06 12:02:54 +02:00
|
|
|
files.add(f);
|
2022-01-24 21:32:18 +01:00
|
|
|
}
|
2022-01-02 09:00:49 +01:00
|
|
|
}
|
2022-01-24 21:32:18 +01:00
|
|
|
return files;
|
2021-10-06 22:32:36 +02:00
|
|
|
}
|
2021-11-01 10:50:13 +01:00
|
|
|
|
2021-12-07 19:42:25 +01:00
|
|
|
final DiContainer _c;
|
2021-10-06 22:32:36 +02:00
|
|
|
}
|
2022-06-06 12:02:54 +02:00
|
|
|
|
|
|
|
Map<int, File> _covertFileMap(List<Object?> dbItems) {
|
|
|
|
return Map.fromEntries(dbItems
|
|
|
|
.whereType<Map>()
|
|
|
|
.map((j) => AppDbFile2Entry.fromJson(j.cast<String, dynamic>()).file)
|
|
|
|
.map((f) => MapEntry(f.fileId!, f)));
|
|
|
|
}
|