DD.WellWorkover.Cloud/AsbCloudWebApi/Controllers/FileController.cs

173 lines
6.9 KiB
C#
Raw Normal View History

using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers
{
2021-08-16 17:34:00 +05:00
[Route("api/well/{idWell}/files")]
[ApiController]
[Authorize]
public class FileController : ControllerBase
{
private readonly IFileService fileService;
private readonly IWellService wellService;
public FileController(IFileService fileService, IWellService wellService)
{
this.fileService = fileService;
this.wellService = wellService;
}
/// <summary>
/// Сохраняет переданные файлы и информацию о них
/// </summary>
2021-07-27 14:43:30 +05:00
/// <param name="idWell">id скважины</param>
/// <param name="idCategory">id категории файла</param>
/// <param name="files">Коллекция файлов</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns>
[HttpPost]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> SaveFilesAsync(int idWell, int idCategory,
[FromForm] IFormFileCollection files, CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
int? idUser = User.GetUserId();
if (idCompany is null || idUser is null)
return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
2021-08-19 17:32:22 +05:00
var fileInfoCollection = files.Select(f => new FileInfoDto
{
Name = f.FileName,
IdCategory = idCategory,
UploadDate = DateTime.Now
});
2021-08-19 17:32:22 +05:00
var fileNamesAndIds = fileService.SaveFileInfos(idWell, (int)idUser,
fileInfoCollection);
foreach (var file in files)
{
var fileExtension = Path.GetExtension(file.FileName);
var fileId = fileNamesAndIds[file.FileName];
var fileStream = file.OpenReadStream();
await fileService.SaveFile(idWell, idCategory, fileId,
fileExtension, fileStream);
}
return Ok();
}
/// <summary>
/// Возвращает информацию о файлах для скважины в выбраной категории
/// </summary>
2021-07-27 14:43:30 +05:00
/// <param name="idWell">id скважины</param>
/// <param name="idCategory">id категории файла</param>
/// <param name="begin">дата начала</param>
/// <param name="end">дата окончания</param>
/// <param name="skip">для пагинации кол-во записей пропустить</param>
/// <param name="take">для пагинации кол-во записей взять </param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>Список информации о файлах в этой категории</returns>
[HttpGet]
[ProducesResponseType(typeof(PaginationContainer<FileInfoDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetFilesInfoAsync([FromRoute] int idWell,
int skip = 0, int take = 32, int idCategory = default,
DateTime begin = default, DateTime end = default, CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
var filesInfo = await fileService.GetFilesInfoAsync(idWell, idCategory,
begin, end, skip, take, token).ConfigureAwait(false);
if (filesInfo is null || !filesInfo.Items.Any())
return NoContent();
return Ok(filesInfo);
}
/// <summary>
/// Возвращает файл с диска на сервере
/// </summary>
2021-07-27 14:43:30 +05:00
/// <param name="idWell">id скважины</param>
/// <param name="fileId">id запрашиваемого файла</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>Запрашиваемый файл</returns>
[HttpGet]
2021-08-16 17:34:00 +05:00
[Route("{fileId}")]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetFileAsync([FromRoute] int idWell,
int fileId, CancellationToken token = default)
{
try
{
int? idCompany = User.GetCompanyId();
if (idCompany is null)
return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
var fileInfo = await fileService.GetFileInfoAsync(fileId, token);
if (fileInfo is null)
throw new FileNotFoundException();
// TODO: словарь content typoв
var relativePath = Path.Combine(fileService.RootPath, $"{idWell}", $"{fileInfo.IdCategory}",
$"{fileInfo.Id}" + Path.GetExtension($"{fileInfo.Name}"));
return PhysicalFile(Path.GetFullPath(relativePath), "application/octet-stream", fileInfo.Name);
}
catch (FileNotFoundException ex)
{
return NotFound($"Файл не найден. Текст ошибки: {ex.Message}");
}
}
/// <summary>
/// Удаляет файл с диска на сервере
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="idFile">id запрашиваемого файла</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns>
[HttpDelete("{idFile}")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> DeleteAsync(int idWell, int idFile,
CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
var result = await fileService.DeleteFileAsync(idFile, token);
return Ok(result);
}
}
}