RobotApp/RobotApp/Controllers/FileController.cs
Đăng Nguyễn 70e27da4a2 update
2025-11-03 10:29:18 +07:00

77 lines
3.5 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RobotApp.Common.Shares;
namespace RobotApp.Controllers;
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class FileController(Services.Logger<FileController> Logger) : ControllerBase
{
private readonly string certificatesPath = "MqttCertificates";
private readonly string caFilePath = "ca";
private readonly string cerFilePath = "cer";
private readonly string keyFilePath = "key";
[HttpPost]
[Route("certificates/{id:guid}")]
public async Task<MessageResult> UpdateMqttCertificates(Guid id, [FromForm(Name = "CaFile")] IFormFile? caFile,
[FromForm(Name = "CertFile")] IFormFile? certFile,
[FromForm(Name = "KeyFile")] IFormFile? keyFile)
{
try
{
if (!Directory.Exists(certificatesPath)) Directory.CreateDirectory(certificatesPath);
if (caFile is not null)
{
var caFolder = Path.Combine(certificatesPath, caFilePath);
if (!Directory.Exists(caFolder)) Directory.CreateDirectory(caFolder);
string caExtension = Path.GetExtension(caFile.FileName);
var caLocal = Path.Combine(caFolder, $"{id}{caExtension}");
if (System.IO.File.Exists($"{caLocal}.bk")) System.IO.File.Delete($"{caLocal}.bk");
if (System.IO.File.Exists(caLocal)) System.IO.File.Move(caLocal, $"{caLocal}.bk");
using Stream fileStream = new FileStream(caLocal, FileMode.Create);
await caFile.OpenReadStream().CopyToAsync(fileStream);
}
if (certFile is not null)
{
var certFolder = Path.Combine(certificatesPath, cerFilePath);
if (!Directory.Exists(certFolder)) Directory.CreateDirectory(certFolder);
string certExtension = Path.GetExtension(certFile.FileName);
var certLocal = Path.Combine(certFolder, $"{id}{certExtension}");
if (System.IO.File.Exists($"{certLocal}.bk")) System.IO.File.Delete($"{certLocal}.bk");
if (System.IO.File.Exists(certLocal)) System.IO.File.Move(certLocal, $"{certLocal}.bk");
using Stream fileStream = new FileStream(certLocal, FileMode.Create);
await certFile.OpenReadStream().CopyToAsync(fileStream);
}
if (keyFile is not null)
{
var keyFolder = Path.Combine(certificatesPath, keyFilePath);
if (!Directory.Exists(keyFolder)) Directory.CreateDirectory(keyFolder);
string keyExtension = Path.GetExtension(keyFile.FileName);
var keyLocal = Path.Combine(keyFolder, $"{id}{keyExtension}");
if (System.IO.File.Exists($"{keyLocal}.bk")) System.IO.File.Delete($"{keyLocal}.bk");
if (System.IO.File.Exists(keyLocal)) System.IO.File.Move(keyLocal, $"{keyLocal}.bk");
using Stream fileStream = new FileStream(keyLocal, FileMode.Create);
await keyFile.OpenReadStream().CopyToAsync(fileStream);
}
return new(true, "");
}
catch (Exception ex)
{
Logger.Error($"Update Mqtt Certificates is failed: {ex.Message}");
return new(false, "An error occurred while retrieving update Mqtt Certificates.");
}
}
}