PutFileBinary creates parent dirs automatically

This commit is contained in:
Ming Ming 2021-05-24 01:24:16 +08:00
parent 7b8ed4885d
commit bea76298dd
2 changed files with 30 additions and 19 deletions

View file

@ -15,7 +15,6 @@ import 'package:nc_photos/int_util.dart' as int_util;
import 'package:nc_photos/iterable_extension.dart';
import 'package:nc_photos/list_extension.dart';
import 'package:nc_photos/remote_storage_util.dart' as remote_storage_util;
import 'package:nc_photos/use_case/create_dir.dart';
import 'package:nc_photos/use_case/get_file_binary.dart';
import 'package:nc_photos/use_case/ls.dart';
import 'package:nc_photos/use_case/put_file_binary.dart';
@ -296,22 +295,9 @@ class AlbumRemoteDataSource implements AlbumDataSource {
final filePath =
"${remote_storage_util.getRemoteAlbumsDir(account)}/$fileName";
final fileRepo = FileRepo(FileWebdavDataSource());
try {
await PutFileBinary(fileRepo)(
account, filePath, utf8.encode(jsonEncode(album.toRemoteJson())));
} on ApiException catch (e) {
if (e.response.statusCode == 404) {
_log.info("[create] Missing album dir, creating");
// no dir
await CreateDir(fileRepo)(
account, remote_storage_util.getRemoteAlbumsDir(account));
// then retry
await PutFileBinary(fileRepo)(
account, filePath, utf8.encode(jsonEncode(album.toRemoteJson())));
} else {
rethrow;
}
}
account, filePath, utf8.encode(jsonEncode(album.toRemoteJson())),
shouldCreateMissingDir: true);
// query album file
final list = await Ls(fileRepo)(account, File(path: filePath),
shouldExcludeRootDir: false);

View file

@ -1,14 +1,39 @@
import 'dart:typed_data';
import 'package:logging/logging.dart';
import 'package:nc_photos/account.dart';
import 'package:nc_photos/entity/file.dart';
import 'package:nc_photos/exception.dart';
import 'package:nc_photos/use_case/create_dir.dart';
import 'package:path/path.dart' as path_lib;
class PutFileBinary {
PutFileBinary(this.fileRepo);
/// Upload file to [path]
Future<void> call(Account account, String path, Uint8List content) =>
fileRepo.putBinary(account, path, content);
Future<void> call(
Account account,
String path,
Uint8List content, {
bool shouldCreateMissingDir = false,
}) async {
try {
await fileRepo.putBinary(account, path, content);
} catch (e) {
if (e is ApiException &&
e.response.statusCode == 404 &&
shouldCreateMissingDir) {
// no dir
_log.info("[call] Auto creating parent dirs");
await CreateDir(fileRepo)(account, path_lib.dirname(path));
await fileRepo.putBinary(account, path, content);
} else {
rethrow;
}
}
}
final FileRepo fileRepo;
static final _log = Logger("use_case.put_file_binary.PutFileBinary");
}