Create and Restore Backups.

This commit is contained in:
DESKTOP-GENO133\IvanPlex 2024-01-17 11:02:40 -07:00
parent 36339a04e1
commit 0714ec6432
5 changed files with 184 additions and 12 deletions

View File

@ -46,12 +46,25 @@ namespace CarCareTracker.Controllers
} }
[HttpPost] [HttpPost]
public ActionResult DeleteFiles(string fileLocation) public IActionResult DeleteFiles(string fileLocation)
{ {
var result = _fileHelper.DeleteFile(fileLocation); var result = _fileHelper.DeleteFile(fileLocation);
return Json(result); return Json(result);
} }
[Authorize(Roles = nameof(UserData.IsRootUser))]
[HttpGet]
public IActionResult MakeBackup()
{
var result = _fileHelper.MakeBackup();
return Json(result);
}
[Authorize(Roles = nameof(UserData.IsRootUser))]
[HttpPost]
public IActionResult RestoreBackup(string fileName)
{
var result = _fileHelper.RestoreBackup(fileName);
return Json(result);
}
private string UploadFile(IFormFile fileToUpload) private string UploadFile(IFormFile fileToUpload)
{ {
string uploadDirectory = "temp/"; string uploadDirectory = "temp/";

View File

@ -1,12 +1,16 @@
namespace CarCareTracker.Helper using System.IO.Compression;
namespace CarCareTracker.Helper
{ {
public interface IFileHelper public interface IFileHelper
{ {
string GetFullFilePath(string currentFilePath, bool mustExist = true); string GetFullFilePath(string currentFilePath, bool mustExist = true);
string MoveFileFromTemp(string currentFilePath, string newFolder); string MoveFileFromTemp(string currentFilePath, string newFolder);
bool DeleteFile(string currentFilePath); bool DeleteFile(string currentFilePath);
string MakeBackup();
bool RestoreBackup(string fileName);
} }
public class FileHelper: IFileHelper public class FileHelper : IFileHelper
{ {
private readonly IWebHostEnvironment _webEnv; private readonly IWebHostEnvironment _webEnv;
public FileHelper(IWebHostEnvironment webEnv) public FileHelper(IWebHostEnvironment webEnv)
@ -23,7 +27,8 @@
if (File.Exists(oldFilePath)) if (File.Exists(oldFilePath))
{ {
return oldFilePath; return oldFilePath;
} else if (!mustExist) }
else if (!mustExist)
{ {
return oldFilePath; return oldFilePath;
} }
@ -31,6 +36,111 @@
return string.Empty; return string.Empty;
} }
} }
public bool RestoreBackup(string fileName)
{
var fullFilePath = GetFullFilePath(fileName);
if (string.IsNullOrWhiteSpace(fullFilePath))
{
return false;
}
try
{
var tempPath = Path.Combine(_webEnv.WebRootPath, $"temp/{Guid.NewGuid()}");
if (!Directory.Exists(tempPath))
Directory.CreateDirectory(tempPath);
//extract zip file
ZipFile.ExtractToDirectory(fullFilePath, tempPath);
//copy over images and documents.
var imagePath = Path.Combine(tempPath, "images");
var documentPath = Path.Combine(tempPath, "documents");
var dataPath = Path.Combine(tempPath, StaticHelper.DbName);
var configPath = Path.Combine(tempPath, StaticHelper.UserConfigPath);
if (Directory.Exists(imagePath))
{
var existingPath = Path.Combine(_webEnv.WebRootPath, "images");
if (Directory.Exists(existingPath))
{
Directory.Delete(existingPath, true);
}
Directory.Move(imagePath, existingPath);
}
if (Directory.Exists(documentPath))
{
var existingPath = Path.Combine(_webEnv.WebRootPath, "documents");
if (Directory.Exists(existingPath))
{
Directory.Delete(existingPath, true);
}
Directory.Move(documentPath, existingPath);
}
if (File.Exists(dataPath))
{
//data path will always exist as it is created on startup if not.
File.Move(dataPath, StaticHelper.DbName, true);
}
if (File.Exists(configPath))
{
//check if config folder exists.
if (!Directory.Exists("config/"))
{
Directory.CreateDirectory("config/");
}
File.Move(configPath, StaticHelper.UserConfigPath, true);
}
return true;
} catch (Exception ex)
{
return false;
}
}
public string MakeBackup()
{
var folderName = $"db_backup_{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}";
var tempPath = Path.Combine(_webEnv.WebRootPath, $"temp/{folderName}");
var imagePath = Path.Combine(_webEnv.WebRootPath, "images");
var documentPath = Path.Combine(_webEnv.WebRootPath, "documents");
var dataPath = StaticHelper.DbName;
var configPath = StaticHelper.UserConfigPath;
if (!Directory.Exists(tempPath))
Directory.CreateDirectory(tempPath);
if (Directory.Exists(imagePath))
{
var files = Directory.GetFiles(imagePath);
foreach (var file in files)
{
var newPath = Path.Combine(tempPath, "images");
Directory.CreateDirectory(newPath);
File.Copy(file, $"{newPath}/{Path.GetFileName(file)}");
}
}
if (Directory.Exists(documentPath))
{
var files = Directory.GetFiles(documentPath);
foreach (var file in files)
{
var newPath = Path.Combine(tempPath, "documents");
Directory.CreateDirectory(newPath);
File.Copy(file, $"{newPath}/{Path.GetFileName(file)}");
}
}
if (File.Exists(dataPath))
{
var newPath = Path.Combine(tempPath, "data");
Directory.CreateDirectory(newPath);
File.Copy(dataPath, $"{newPath}/{Path.GetFileName(dataPath)}");
}
if (File.Exists(configPath))
{
var newPath = Path.Combine(tempPath, "config");
Directory.CreateDirectory(newPath);
File.Copy(configPath, $"{newPath}/{Path.GetFileName(configPath)}");
}
var destFilePath = $"{tempPath}.zip";
ZipFile.CreateFromDirectory(tempPath, destFilePath);
//delete temp directory
Directory.Delete(tempPath, true);
return $"/temp/{folderName}.zip";
}
public string MoveFileFromTemp(string currentFilePath, string newFolder) public string MoveFileFromTemp(string currentFilePath, string newFolder)
{ {
string tempPath = "temp/"; string tempPath = "temp/";
@ -38,7 +148,8 @@
{ {
return currentFilePath; return currentFilePath;
} }
if (currentFilePath.StartsWith("/")) { if (currentFilePath.StartsWith("/"))
{
currentFilePath = currentFilePath.Substring(1); currentFilePath = currentFilePath.Substring(1);
} }
string uploadPath = Path.Combine(_webEnv.WebRootPath, newFolder); string uploadPath = Path.Combine(_webEnv.WebRootPath, newFolder);
@ -67,7 +178,8 @@
if (!File.Exists(filePath)) //verify file no longer exists. if (!File.Exists(filePath)) //verify file no longer exists.
{ {
return true; return true;
} else }
else
{ {
return false; return false;
} }

View File

@ -94,10 +94,8 @@
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-12">
<span class="lead">Default Tab</span>
</div>
<div class="col-12 col-md-6"> <div class="col-12 col-md-6">
<span class="lead">Default Tab</span>
<select class="form-select" onchange="updateSettings()" id="defaultTab"> <select class="form-select" onchange="updateSettings()" id="defaultTab">
<!option @(StaticHelper.DefaultTabSelected(Model, ImportMode.Dashboard)) value="Dashboard">Dashboard</!option> <!option @(StaticHelper.DefaultTabSelected(Model, ImportMode.Dashboard)) value="Dashboard">Dashboard</!option>
<!option @(StaticHelper.DefaultTabSelected(Model,ImportMode.ServiceRecord)) value="ServiceRecord">Service Record</!option> <!option @(StaticHelper.DefaultTabSelected(Model,ImportMode.ServiceRecord)) value="ServiceRecord">Service Record</!option>
@ -110,6 +108,21 @@
<!option @(StaticHelper.DefaultTabSelected(Model, ImportMode.SupplyRecord)) value="SupplyRecord">Supplies</!option> <!option @(StaticHelper.DefaultTabSelected(Model, ImportMode.SupplyRecord)) value="SupplyRecord">Supplies</!option>
</select> </select>
</div> </div>
@if (User.IsInRole(nameof(UserData.IsRootUser)))
{
<div class="col-12 col-md-6">
<span class="lead">Backups</span>
<div class="row">
<div class="col-6 d-grid">
<button onclick="makeBackup()" class="btn btn-primary btn-md">Make</button>
</div>
<div class="col-6 d-grid">
<input onChange="restoreBackup(this)" type="file" accept=".zip" class="d-none" id="inputBackup">
<button onclick="openRestoreBackup()" class="btn btn-secondary btn-md">Restore</button>
</div>
</div>
</div>
}
</div> </div>
</div> </div>
</div> </div>
@ -187,6 +200,40 @@
} }
}) })
} }
function makeBackup() {
$.get('/Files/MakeBackup', function (data) {
window.location.href = data;
});
}
function openRestoreBackup(){
$("#inputBackup").click();
}
function restoreBackup(event) {
let formData = new FormData();
formData.append("file", event.files[0]);
sloader.show();
$.ajax({
url: "/Files/HandleFileUpload",
data: formData,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (response) {
if (response.trim() != '') {
$.post('/Files/RestoreBackup', { fileName : response}, function (data) {
sloader.hide();
if (data){
successToast("Backup Restored");
setTimeout(function () { window.location.href = '/Home/Index' }, 500);
} else {
errorToast("An error occurred, please try again later.");
}
});
}
}
});
}
function enableAuthCheckChanged(){ function enableAuthCheckChanged(){
var enableAuth = $("#enableAuth").is(":checked"); var enableAuth = $("#enableAuth").is(":checked");
if (enableAuth) { if (enableAuth) {

View File

@ -9,7 +9,7 @@
new Chart($("#pie-chart"), { new Chart($("#pie-chart"), {
type: 'pie', type: 'pie',
data: { data: {
labels: ["Planned Maintenance(Service Records)", "Unplanned Maintenance(Repairs)", "Upgrades", "Tax", "Fuel"], labels: ["Service Records", "Repairs", "Upgrades", "Tax", "Fuel"],
datasets: [ datasets: [
{ {
label: "Expenses by Category", label: "Expenses by Category",

View File

@ -93,7 +93,7 @@ function getAndValidateSupplyRecordValues() {
} else { } else {
$("#supplyRecordDescription").removeClass("is-invalid"); $("#supplyRecordDescription").removeClass("is-invalid");
} }
if (supplyQuantity.trim() == '' || !isValidMoney(supplyQuantity)) { if (supplyQuantity.trim() == '' || !isValidMoney(supplyQuantity) || parseFloat(supplyQuantity) < 0) {
hasError = true; hasError = true;
$("#supplyRecordQuantity").addClass("is-invalid"); $("#supplyRecordQuantity").addClass("is-invalid");
} else { } else {