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.Repositories;
using Microsoft.AspNetCore.Authorization;
using System.Net;
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 категории файла
/// Файл справки
/// Токен для отмены задачи
///
[HttpPost]
[Permission]
[Route("upload")]
[ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
public async Task UploadAsync(string urlPage,
int idCategory,
[Required] IFormFile file,
CancellationToken cancellationToken)
{
int? idUser = User.GetUserId();
if(!idUser.HasValue)
return Forbid();
if (!userRepository.HasPermission(idUser.Value, $"HelpPage.edit"))
return Forbid();
using var fileStream = file.OpenReadStream();
int helpPageId = await helpPageService.AddOrUpdateAsync(urlPage,
idCategory,
file.FileName,
fileStream,
cancellationToken);
return Ok(helpPageId);
}
///
/// Получение файла справки
///
/// Url страницы
/// Id категории файла
/// Токен для отмены задачи
///
[HttpGet]
[Route("get/{urlPage}/{idCategory}")]
[ProducesResponseType(typeof(PhysicalFileResult), (int)HttpStatusCode.OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task GetFileAsync(string urlPage,
int idCategory,
CancellationToken cancellationToken)
{
var file = await helpPageService.GetFileStreamAsync(urlPage,
idCategory,
cancellationToken);
using var fileStream = file.stream;
var memoryStream = new MemoryStream();
await fileStream.CopyToAsync(memoryStream,
cancellationToken);
memoryStream.Position = 0;
return File(memoryStream, "application/octet-stream", file.fileName);
}
}