Rename file if the same name exists in destination

This commit is contained in:
Ming Ming 2021-08-27 01:28:58 +08:00
parent 0689040ccc
commit 2a462cf906
2 changed files with 64 additions and 10 deletions

View file

@ -17,17 +17,54 @@ class Move {
File file,
String destination, {
bool shouldCreateMissingDir = false,
bool shouldOverwrite = false,
bool shouldRenameOnOverwrite = false,
}) =>
_doWork(
account,
file,
destination,
shouldCreateMissingDir: shouldCreateMissingDir,
shouldOverwrite: shouldOverwrite,
shouldRenameOnOverwrite: shouldRenameOnOverwrite,
);
Future<void> _doWork(
Account account,
File file,
String destination, {
required bool shouldCreateMissingDir,
required bool shouldOverwrite,
required bool shouldRenameOnOverwrite,
int retryCount = 1,
}) async {
final to = _renameDestination(destination, retryCount);
if (retryCount > 1) {
_log.info("[call] Retry with: '$to'");
}
try {
await fileRepo.move(account, file, destination);
await fileRepo.move(account, file, to, shouldOverwrite: shouldOverwrite);
} catch (e) {
if (e is ApiException &&
e.response.statusCode == 409 &&
shouldCreateMissingDir) {
// no dir
_log.info("[call] Auto creating parent dirs");
await CreateDir(fileRepo)(account, path.dirname(destination));
await fileRepo.move(account, file, destination);
if (e is ApiException) {
if (e.response.statusCode == 409 && shouldCreateMissingDir) {
// no dir
_log.info("[call] Auto creating parent dirs");
await CreateDir(fileRepo)(account, path.dirname(to));
await fileRepo.move(account, file, to,
shouldOverwrite: shouldOverwrite);
} else if (e.response.statusCode == 412 && shouldRenameOnOverwrite) {
return _doWork(
account,
file,
to,
shouldCreateMissingDir: shouldCreateMissingDir,
shouldOverwrite: shouldOverwrite,
shouldRenameOnOverwrite: shouldRenameOnOverwrite,
retryCount: retryCount + 1,
);
} else {
rethrow;
}
} else {
rethrow;
}
@ -37,6 +74,19 @@ class Move {
.fire(FileMovedEvent(account, file, destination));
}
String _renameDestination(String destination, int retryCount) {
if (retryCount < 2) {
return destination;
}
final temp =
"${path.dirname(destination)}/${path.basenameWithoutExtension(destination)} ($retryCount)";
if (path.extension(destination).isEmpty) {
return temp;
} else {
return "$temp.${path.extension(destination)}";
}
}
final FileRepo fileRepo;
static final _log = Logger("use_case.move.Move");

View file

@ -10,8 +10,12 @@ class RestoreTrashbin {
RestoreTrashbin(this.fileRepo);
Future<void> call(Account account, File file) async {
await Move(fileRepo).call(account, file,
"remote.php/dav/trashbin/${account.username}/restore/${path.basename(file.path)}");
await Move(fileRepo)(
account,
file,
"remote.php/dav/trashbin/${account.username}/restore/${path.basename(file.path)}",
shouldOverwrite: true,
);
KiwiContainer()
.resolve<EventBus>()
.fire(FileTrashbinRestoredEvent(account, file));