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

149 lines
6.2 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
{
[Route("api/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="idUser">id отправившего файл пользователя</param>
/// <param name="files">Коллекция файлов</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns>
[HttpPost]
2021-07-27 14:43:30 +05:00
[Route("{idWell}/files")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> SaveFilesAsync(int idWell, int idCategory,
int idUser, [FromForm] IFormFileCollection files, CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
if (idCompany is null)
return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
var fileInfoCollection = files.Select(f =>
2021-07-27 14:43:30 +05:00
(f.FileName, idWell, idCategory, DateTime.Now, idUser));
2021-07-27 14:43:30 +05:00
var fileNamesAndIds = fileService.SaveFilesPropertiesToDb(idWell,
idCategory, fileInfoCollection);
foreach (var file in files)
{
var fileExtension = Path.GetExtension(file.FileName);
var fileId = fileNamesAndIds[file.FileName];
2021-07-27 14:43:30 +05:00
var relativePath = Path.Combine(fileService.RootPath, $"{idWell}",
$"{idCategory}", $"{fileId}" + $"{fileExtension}");
Directory.CreateDirectory(Path.GetDirectoryName(relativePath));
using var fileStream = new FileStream(relativePath, FileMode.Create);
file.CopyTo(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]
2021-07-27 14:43:30 +05:00
[Route("{idWell}")]
[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-07-27 14:43:30 +05:00
[Route("{idWell}/{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}");
}
}
}
}