2020-04-08 15:27:40 +02:00
|
|
|
|
using System;
|
|
|
|
|
using MediatR;
|
2020-03-24 13:01:14 +01:00
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using ModernKeePass.Application.Common.Interfaces;
|
|
|
|
|
using ModernKeePass.Domain.Exceptions;
|
|
|
|
|
|
|
|
|
|
namespace ModernKeePass.Application.Database.Commands.SaveDatabase
|
|
|
|
|
{
|
|
|
|
|
public class SaveDatabaseCommand : IRequest
|
|
|
|
|
{
|
2020-03-27 18:45:13 +01:00
|
|
|
|
public string FilePath { get; set; }
|
2020-03-24 17:31:34 +01:00
|
|
|
|
|
|
|
|
|
public class SaveDatabaseCommandHandler : IAsyncRequestHandler<SaveDatabaseCommand>
|
2020-03-24 13:01:14 +01:00
|
|
|
|
{
|
|
|
|
|
private readonly IDatabaseProxy _database;
|
2020-04-06 20:20:45 +02:00
|
|
|
|
private readonly IFileProxy _file;
|
2020-03-24 13:01:14 +01:00
|
|
|
|
|
2020-04-06 20:20:45 +02:00
|
|
|
|
public SaveDatabaseCommandHandler(IDatabaseProxy database, IFileProxy file)
|
2020-03-24 13:01:14 +01:00
|
|
|
|
{
|
|
|
|
|
_database = database;
|
2020-04-06 20:20:45 +02:00
|
|
|
|
_file = file;
|
2020-03-24 13:01:14 +01:00
|
|
|
|
}
|
|
|
|
|
|
2020-03-24 17:31:34 +01:00
|
|
|
|
public async Task Handle(SaveDatabaseCommand message)
|
2020-03-24 13:01:14 +01:00
|
|
|
|
{
|
2020-03-26 19:04:51 +01:00
|
|
|
|
if (!_database.IsOpen) throw new DatabaseClosedException();
|
|
|
|
|
|
2020-04-08 15:27:40 +02:00
|
|
|
|
try
|
2020-04-06 20:20:45 +02:00
|
|
|
|
{
|
2020-04-08 15:27:40 +02:00
|
|
|
|
byte[] contents;
|
|
|
|
|
if (string.IsNullOrEmpty(message.FilePath))
|
|
|
|
|
{
|
|
|
|
|
contents = await _database.SaveDatabase();
|
|
|
|
|
|
|
|
|
|
// Test DB integrity before writing changes to file
|
|
|
|
|
_database.CloseDatabase();
|
|
|
|
|
var file = await _file.OpenBinaryFile(_database.FileAccessToken);
|
|
|
|
|
await _database.ReOpen(file);
|
|
|
|
|
|
|
|
|
|
await _file.WriteBinaryContentsToFile(_database.FileAccessToken, contents);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
var newFileContents = await _file.OpenBinaryFile(message.FilePath);
|
|
|
|
|
contents = await _database.SaveDatabase(newFileContents);
|
|
|
|
|
await _file.WriteBinaryContentsToFile(message.FilePath, contents);
|
|
|
|
|
|
|
|
|
|
_file.ReleaseFile(_database.FileAccessToken);
|
|
|
|
|
_database.FileAccessToken = message.FilePath;
|
|
|
|
|
}
|
2020-04-06 20:20:45 +02:00
|
|
|
|
}
|
2020-04-08 15:27:40 +02:00
|
|
|
|
catch (Exception exception)
|
2020-04-06 20:20:45 +02:00
|
|
|
|
{
|
2020-04-08 15:27:40 +02:00
|
|
|
|
throw new SaveException(exception);
|
2020-04-06 20:20:45 +02:00
|
|
|
|
}
|
2020-03-24 13:01:14 +01:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|