using AsbCloudApp.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Repositories;
using Microsoft.AspNetCore.Authorization;
namespace AsbCloudWebApi.Controllers;
///
/// Справки по страницам
///
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class HelpPageController : ControllerBase
{
private readonly IHelpPageService helpPageService;
private readonly IUserRepository userRepository;
public HelpPageController(IHelpPageService helpPageService,
IUserRepository userRepository)
{
this.helpPageService = helpPageService;
this.userRepository = userRepository;
}
///
/// Создание файла справки
///
/// Url страницы для которой предназначена эта справка
/// Id катагории файла
/// Загружаемый файл
/// Id созданной справки
[HttpPost]
[Permission]
[Route("saveFile")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task CreateAsync(string urlPage,
int idCategory,
[Required] IFormFile file)
{
int? idUser = User.GetUserId();
if(!idUser.HasValue)
return Forbid();
if (!userRepository.HasPermission(idUser.Value, $"HelpPage.create"))
return Forbid();
var helpPage = await helpPageService.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage,
idCategory,
CancellationToken.None);
using var fileStream = file.OpenReadStream();
if (helpPage is not null)
{
await helpPageService.UpdateAsync(helpPage,
idCategory,
file.FileName,
fileStream,
CancellationToken.None);
return Ok(helpPage.Id);
}
int helpPageId = await helpPageService.CreateAsync(urlPage,
idCategory,
file.FileName,
fileStream,
CancellationToken.None);
return Ok(helpPageId);
}
///
/// Получение файла справки
///
/// Id справки
/// Файл
[HttpGet]
[Route("getById/{id}")]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
public async Task GetFileAsync(int id)
{
var helpPage = await helpPageService.GetOrDefaultByIdAsync(id,
CancellationToken.None);
if (helpPage is null)
return NotFound();
using var fileStream = helpPageService.GetFileStream(helpPage);
var memoryStream = new MemoryStream();
await fileStream.CopyToAsync(memoryStream,
CancellationToken.None);
memoryStream.Position = 0;
return File(memoryStream, "application/octet-stream", helpPage.Name);
}
///
/// Получение информации о справке
///
/// Url страницы
/// Id категории
/// Dto справки
[HttpGet]
[Route("getByUrlPage/{urlPage}/{idCategory}")]
[ProducesResponseType(typeof(HelpPageDto), (int)System.Net.HttpStatusCode.OK)]
public async Task GetByUrlPageAsync(string urlPage,
int idCategory)
{
var helpPage = await helpPageService.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage,
idCategory,
CancellationToken.None);
return Ok(helpPage);
}
}