DD.WellWorkover.Cloud/AsbCloudWebApi/Controllers/FileController.cs
2021-07-27 14:43:30 +05:00

140 lines
5.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Linq;
using System.IO;
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
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>
/// <param name="idWell">id скважины</param>
/// <param name="idCategory">id категории файла</param>
/// <param name="idUser">id отправившего файл пользователя</param>
/// <param name="files">Коллекция файлов</param>
/// <returns></returns>
[HttpPost]
[Route("{idWell}/files")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public IActionResult SaveFiles(int idWell, int idCategory, int idUser,
[FromForm] IFormFileCollection files)
{
int? idCompany = User.GetCompanyId();
if (idCompany is null)
return Forbid();
if (!wellService.IsCompanyOwnsWell((int)idCompany, idWell))
return Forbid();
var fileInfoCollection = files.Select(f =>
(f.FileName, idWell, idCategory, DateTime.Now, idUser));
var fileNamesAndIds = fileService.SaveFilesPropertiesToDb(idWell,
idCategory, fileInfoCollection);
foreach (var file in files)
{
var fileExtension = Path.GetExtension(file.FileName);
var fileId = fileNamesAndIds[file.FileName];
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>
/// <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>
/// <returns>Список информации о файлах в этой категории</returns>
[HttpGet]
[Route("{idWell}")]
[ProducesResponseType(typeof(PaginationContainer<FilePropertiesDto>), (int)System.Net.HttpStatusCode.OK)]
public IActionResult GetFilesInfo([FromRoute] int idWell,
int skip = 0, int take = 32, int idCategory = default,
DateTime begin = default, DateTime end = default)
{
int? idCompany = User.GetCompanyId();
if (idCompany is null || !wellService.IsCompanyOwnsWell((int)idCompany, idWell))
return Forbid();
var filesInfo = fileService.GetFilesInfo(idWell, idCategory,
begin, end, skip, take);
if (filesInfo is null || !filesInfo.Items.Any())
return NoContent();
return Ok(filesInfo);
}
/// <summary>
/// Возвращает файл с диска на сервере
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="fileId">id запрашиваемого файла</param>
/// <returns>Запрашиваемый файл</returns>
[HttpGet]
[Route("{idWell}/{fileId}")]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
public IActionResult GetFile([FromRoute] int idWell, int fileId)
{
try
{
int? idCompany = User.GetCompanyId();
if (idCompany is null)
return Forbid();
if (!wellService.IsCompanyOwnsWell((int)idCompany, idWell))
return Forbid();
var fileInfo = fileService.GetFileInfo(fileId);
if (fileInfo is null)
throw new FileNotFoundException();
// TODO: словарь content typoв
var relativePath = Path.Combine(fileService.RootPath, $"{idWell}", $"{fileInfo.Value.IdCategory}",
$"{fileInfo.Value.Id}" + Path.GetExtension($"{fileInfo.Value.Name}"));
return PhysicalFile(Path.GetFullPath(relativePath), "application/octet-stream", fileInfo.Value.Name);
}
catch (FileNotFoundException ex)
{
return NotFound($"Файл не найден. Текст ошибки: {ex.Message}");
}
}
}
}