82 lines
No EOL
2.6 KiB
C#
82 lines
No EOL
2.6 KiB
C#
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Http.HttpResults;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Mizuki.Dtos;
|
|
using Mizuki.Services;
|
|
using Mizuki.Validators;
|
|
|
|
namespace Mizuki.Controllers;
|
|
|
|
/// <summary>
|
|
/// The file api
|
|
/// </summary>
|
|
/// <param name="uploadService"></param>
|
|
[Authorize]
|
|
[Route("/api/file")]
|
|
public class FileController(
|
|
UploadService uploadService,
|
|
LoginService loginService,
|
|
FormFileValidator formFileValidator)
|
|
{
|
|
/// <summary>
|
|
/// Creates a new file.
|
|
/// </summary>
|
|
/// <param name="formFile">The given file.</param>
|
|
/// <returns>Either the result, or an error.</returns>
|
|
[HttpPost]
|
|
[Route("upload")]
|
|
public async Task<Results<Ok<FileCreationResultDto>, BadRequest<FileCreationErrorDto>>> UploadFile(
|
|
IFormFile formFile)
|
|
{
|
|
var result = await formFileValidator.ValidateAsync(formFile);
|
|
if (!result.IsValid)
|
|
{
|
|
if (result.Errors.Any(e => e.PropertyName == "Length"))
|
|
return TypedResults.BadRequest(new FileCreationErrorDto("The file is too big. (Max is 50MiB)"));
|
|
|
|
if (result.Errors.Any(e => e.PropertyName == "Filename"))
|
|
return TypedResults.BadRequest(new FileCreationErrorDto("Invalid filename."));
|
|
|
|
return TypedResults.BadRequest(new FileCreationErrorDto("Unknown validation error."));
|
|
}
|
|
|
|
var user = await loginService.GetActiveUser();
|
|
var upload = await uploadService.CreateUpload(user, formFile);
|
|
if (upload is null)
|
|
{
|
|
return TypedResults.BadRequest(new FileCreationErrorDto("There was a problem processing your upload, please try again later."));
|
|
}
|
|
|
|
return TypedResults.Ok(new FileCreationResultDto(upload.Filename));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Lists all of the files for the logged in user.
|
|
/// </summary>
|
|
/// <returns>The list of all files this user has.</returns>
|
|
[HttpGet]
|
|
[Route("all")]
|
|
public async Task<IEnumerable<FileDto>> ListAllFiles()
|
|
{
|
|
var user = await loginService.GetActiveUser();
|
|
var uploads = await uploadService.GetAllUploadsForUser(user);
|
|
|
|
return uploads.Select(u => new FileDto(
|
|
u.Filename,
|
|
u.OriginalFilename,
|
|
u.SizeInBytes));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Deletes a file.
|
|
/// </summary>
|
|
/// <param name="filename">The filename of the file.</param>
|
|
[HttpGet]
|
|
[Route("delete")]
|
|
public async Task DeleteFile(
|
|
[FromQuery] string filename)
|
|
{
|
|
var user = await loginService.GetActiveUser();
|
|
await uploadService.DeleteUpload(user, filename);
|
|
}
|
|
} |