diff --git a/AsbCloudApp/Data/HelpPageDto.cs b/AsbCloudApp/Data/HelpPageDto.cs index 35f58700..22931c3b 100644 --- a/AsbCloudApp/Data/HelpPageDto.cs +++ b/AsbCloudApp/Data/HelpPageDto.cs @@ -2,6 +2,9 @@ namespace AsbCloudApp.Data; +/// +/// Справка по страницам +/// public class HelpPageDto : IId { /// diff --git a/AsbCloudApp/Exceptions/ArgumentInvalidException.cs b/AsbCloudApp/Exceptions/ArgumentInvalidException.cs index 4b1abd34..987401bc 100644 --- a/AsbCloudApp/Exceptions/ArgumentInvalidException.cs +++ b/AsbCloudApp/Exceptions/ArgumentInvalidException.cs @@ -1,13 +1,11 @@ using System; -using AsbCloudApp.Exceptions.Interfaces; namespace AsbCloudApp.Exceptions { /// /// Argument validation fail Exception /// - public class ArgumentInvalidException : Exception, - IHasValidation + public class ArgumentInvalidException : Exception { /// /// название аргумента diff --git a/AsbCloudApp/Exceptions/ArgumentsInvalidException.cs b/AsbCloudApp/Exceptions/ArgumentsInvalidException.cs deleted file mode 100644 index 7c1b7d83..00000000 --- a/AsbCloudApp/Exceptions/ArgumentsInvalidException.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using AsbCloudApp.Exceptions.Interfaces; - -namespace AsbCloudApp.Exceptions; - -/// -/// Исключение для нескольких невалидных агрументов -/// -public class ArgumentsInvalidException : Exception, - IHasValidation -{ - /// - /// Имена параметров - /// - public string[] ParamNames { get; } = Array.Empty(); - - /// - /// Контсруктор исключения - /// - /// - /// - public ArgumentsInvalidException(string message, - string[] paramNames) - { - ParamNames = paramNames; - } - - /// - /// преобразование в объект валидации - /// - /// - public object ToValidationErrorObject() - => MakeValidationError(ParamNames, Message); - - /// - /// фабрика объекта валидации - /// - /// - /// - /// - public static object MakeValidationError(string[] paramNames, params string[] errors) - => new - { - names = paramNames, - errors, - }; -} \ No newline at end of file diff --git a/AsbCloudApp/Exceptions/Interfaces/IHasValidation.cs b/AsbCloudApp/Exceptions/Interfaces/IHasValidation.cs deleted file mode 100644 index 6b70ed79..00000000 --- a/AsbCloudApp/Exceptions/Interfaces/IHasValidation.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace AsbCloudApp.Exceptions.Interfaces; - -/// -/// Интерфейс конвертации исключений -/// -public interface IHasValidation -{ - /// - /// Интерфейс конвертации исключений - /// - /// - object ToValidationErrorObject(); -} \ No newline at end of file diff --git a/AsbCloudApp/Repositories/IHelpPageRepository.cs b/AsbCloudApp/Repositories/IHelpPageRepository.cs index aa56a424..26f9c69e 100644 --- a/AsbCloudApp/Repositories/IHelpPageRepository.cs +++ b/AsbCloudApp/Repositories/IHelpPageRepository.cs @@ -20,15 +20,4 @@ public interface IHelpPageRepository : ICrudRepository Task GetOrDefaultByUrlPageAndIdCategoryAsync(string urlPage, int idCategory, CancellationToken cancellationToken); - - /// - /// Проверка на существование справки для определённой страницы в категории - /// - /// - /// - /// - /// - Task IsCheckHelpPageWithUrlPageAndIdCategoryAsync(string urlPage, - int idCategory, - CancellationToken cancellationToken); } diff --git a/AsbCloudApp/Services/IHelpPageService.cs b/AsbCloudApp/Services/IHelpPageService.cs index 726f4566..04051521 100644 --- a/AsbCloudApp/Services/IHelpPageService.cs +++ b/AsbCloudApp/Services/IHelpPageService.cs @@ -1,5 +1,4 @@ -using AsbCloudApp.Data; -using System.IO; +using System.IO; using System.Threading; using System.Threading.Tasks; @@ -11,7 +10,7 @@ namespace AsbCloudApp.Services; public interface IHelpPageService { /// - /// Создание справки + /// Метод обновления или обновления файла справки /// /// /// @@ -19,52 +18,20 @@ public interface IHelpPageService /// /// /// - Task CreateAsync(string urlPage, - int idCategory, - string fileName, - Stream fileStream, - CancellationToken cancellationToken); - - /// - /// Редактирование справки - /// - /// - /// - /// - /// - /// - /// - Task UpdateAsync(HelpPageDto helpPage, + Task AddOrUpdateAsync(string urlPage, int idCategory, string fileName, Stream fileStream, CancellationToken cancellationToken); /// - /// Получение справки по url страницы и id категории + /// Метод получения файла справки /// /// /// /// /// - Task GetOrDefaultByUrlPageAndIdCategoryAsync(string urlPage, + Task<(Stream stream, string fileName)> GetFileStreamAsync(string urlPage, int idCategory, CancellationToken cancellationToken); - - /// - /// Получение справки по Id - /// - /// - /// - /// - Task GetOrDefaultByIdAsync(int id, - CancellationToken cancellationToken); - - /// - /// Получение файла справки по Id - /// - /// - /// - /// - Stream GetFileStream(HelpPageDto helpPage); } \ No newline at end of file diff --git a/AsbCloudDb/Migrations/20230628103733_Add_New_Init_Value_For_Permission.Designer.cs b/AsbCloudDb/Migrations/20230628103733_Add_New_Init_Value_For_Permission.Designer.cs index 8e58f715..f695736f 100644 --- a/AsbCloudDb/Migrations/20230628103733_Add_New_Init_Value_For_Permission.Designer.cs +++ b/AsbCloudDb/Migrations/20230628103733_Add_New_Init_Value_For_Permission.Designer.cs @@ -2054,7 +2054,7 @@ namespace AsbCloudDb.Migrations { Id = 519, Description = "Разрешить создание справок по страницам", - Name = "HelpPage.create" + Name = "HelpPage.edit" }); }); diff --git a/AsbCloudDb/Migrations/20230628103733_Add_New_Init_Value_For_Permission.cs b/AsbCloudDb/Migrations/20230628103733_Add_New_Init_Value_For_Permission.cs index 1deb614e..17de1012 100644 --- a/AsbCloudDb/Migrations/20230628103733_Add_New_Init_Value_For_Permission.cs +++ b/AsbCloudDb/Migrations/20230628103733_Add_New_Init_Value_For_Permission.cs @@ -11,7 +11,7 @@ namespace AsbCloudDb.Migrations migrationBuilder.InsertData( table: "t_permission", columns: new[] { "id", "description", "name" }, - values: new object[] { 519, "Разрешить создание справок по страницам", "HelpPage.create" }); + values: new object[] { 519, "Разрешить создание справок по страницам", "HelpPage.edit" }); migrationBuilder.InsertData( table: "t_relation_user_role_permission", diff --git a/AsbCloudDb/Migrations/AsbCloudDbContextModelSnapshot.cs b/AsbCloudDb/Migrations/AsbCloudDbContextModelSnapshot.cs index acb6b7fa..d18fe474 100644 --- a/AsbCloudDb/Migrations/AsbCloudDbContextModelSnapshot.cs +++ b/AsbCloudDb/Migrations/AsbCloudDbContextModelSnapshot.cs @@ -2052,7 +2052,7 @@ namespace AsbCloudDb.Migrations { Id = 519, Description = "Разрешить создание справок по страницам", - Name = "HelpPage.create" + Name = "HelpPage.edit" }); }); diff --git a/AsbCloudDb/Model/DefaultData/EntityFillerPermission.cs b/AsbCloudDb/Model/DefaultData/EntityFillerPermission.cs index 8dfc74dd..462085bb 100644 --- a/AsbCloudDb/Model/DefaultData/EntityFillerPermission.cs +++ b/AsbCloudDb/Model/DefaultData/EntityFillerPermission.cs @@ -150,7 +150,7 @@ new (){ Id = 517, Name="FaqStatistics.edit", Description="Разрешение редактировать вопрос"}, new (){ Id = 518, Name="FaqStatistics.delete", Description="Разрешение удалять вопрос"}, - new() { Id = 519, Name = "HelpPage.create", Description = "Разрешить создание справок по страницам" } + new() { Id = 519, Name = "HelpPage.edit", Description = "Разрешить создание справок по страницам" } }; } } diff --git a/AsbCloudInfrastructure/DependencyInjection.cs b/AsbCloudInfrastructure/DependencyInjection.cs index c3725e5f..69b9fe3d 100644 --- a/AsbCloudInfrastructure/DependencyInjection.cs +++ b/AsbCloudInfrastructure/DependencyInjection.cs @@ -136,12 +136,7 @@ namespace AsbCloudInfrastructure services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(serviceProvider => - new HelpPageService( - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService(), - configuration.GetSection("HelpPageOptions:DirectoryNameHelpPageFiles") - .Get())); + services.AddTransient(); services.AddTransient(); diff --git a/AsbCloudInfrastructure/Repository/HelpPageRepository.cs b/AsbCloudInfrastructure/Repository/HelpPageRepository.cs index 443b56db..dfc912a3 100644 --- a/AsbCloudInfrastructure/Repository/HelpPageRepository.cs +++ b/AsbCloudInfrastructure/Repository/HelpPageRepository.cs @@ -31,13 +31,4 @@ public class HelpPageRepository : CrudRepositoryBase, return helpPage.Adapt(); } - - public Task IsCheckHelpPageWithUrlPageAndIdCategoryAsync(string urlPage, int idCategory, - CancellationToken cancellationToken) - { - return dbSet.AnyAsync(x => - x.UrlPage == urlPage && - x.IdCategory == idCategory, - cancellationToken); - } } diff --git a/AsbCloudInfrastructure/Services/HelpPageService.cs b/AsbCloudInfrastructure/Services/HelpPageService.cs index 7be9e065..1f97312f 100644 --- a/AsbCloudInfrastructure/Services/HelpPageService.cs +++ b/AsbCloudInfrastructure/Services/HelpPageService.cs @@ -1,16 +1,16 @@ -using System; -using AsbCloudApp.Data; +using AsbCloudApp.Data; using AsbCloudApp.Repositories; using AsbCloudApp.Services; using System.IO; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; using AsbCloudApp.Exceptions; namespace AsbCloudInfrastructure.Services; /// -/// Реализация сервиса справок страниц +/// Реализация сервиса для справок по страницам /// public class HelpPageService : IHelpPageService { @@ -23,21 +23,18 @@ public class HelpPageService : IHelpPageService /// /// /// - /// + /// public HelpPageService(IHelpPageRepository helpPageRepository, IFileStorageRepository fileStorageRepository, - string directoryNameHelpPageFiles) - { - if (string.IsNullOrWhiteSpace(directoryNameHelpPageFiles)) - throw new ArgumentException("Value cannot be null or whitespace", nameof(this.directoryNameHelpPageFiles)); - + IConfiguration configuration) + { this.helpPageRepository = helpPageRepository; this.fileStorageRepository = fileStorageRepository; - this.directoryNameHelpPageFiles = directoryNameHelpPageFiles; + directoryNameHelpPageFiles = configuration.GetValue("DirectoryNameHelpPageFiles"); } /// - /// Создание справки страницы + /// Метод обновления или обновления файла справки /// /// /// @@ -45,20 +42,67 @@ public class HelpPageService : IHelpPageService /// /// /// - public async Task CreateAsync(string urlPage, + public async Task AddOrUpdateAsync(string urlPage, + int idCategory, + string fileName, + Stream fileStream, + CancellationToken cancellationToken) + { + var helpPage = await helpPageRepository.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage, + idCategory, + cancellationToken); + + if(helpPage is not null) + { + await UpdateFileAsync(helpPage, + idCategory, + fileName, + fileStream, + cancellationToken); + + return helpPage.Id; + } + + return await SaveFileAsync(urlPage, + idCategory, + fileName, + fileStream, + cancellationToken); + } + + + /// + /// Метод получения файла справки + /// + /// + /// + /// + /// + /// + public async Task<(Stream stream, string fileName)> GetFileStreamAsync(string urlPage, + int idCategory, + CancellationToken cancellationToken) + { + var helpPage = await helpPageRepository.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage, + idCategory, + cancellationToken) ?? throw new ArgumentInvalidException("Справки не существует", nameof(idCategory)); + + string filePath = fileStorageRepository.GetFilePath(directoryNameHelpPageFiles, + helpPage.IdCategory.ToString(), + helpPage.Id, + Path.GetExtension(helpPage.Name)); + + var fileStream = new FileStream(Path.GetFullPath(filePath), FileMode.Open); + + return (fileStream, helpPage.Name); + } + + private async Task SaveFileAsync(string urlPage, int idCategory, string fileName, Stream fileStream, CancellationToken cancellationToken) { - if (await helpPageRepository.IsCheckHelpPageWithUrlPageAndIdCategoryAsync(urlPage, - idCategory, - cancellationToken)) - { - throw new ArgumentsInvalidException("Справка с такой категории файла для данной страницы уже существует", - new[] { nameof(urlPage), nameof(idCategory) }); - } - HelpPageDto helpPage = new() { UrlPage = urlPage, @@ -79,16 +123,7 @@ public class HelpPageService : IHelpPageService return idFile; } - /// - /// Обновление справки страницы - /// - /// - /// - /// - /// - /// - /// - public async Task UpdateAsync(HelpPageDto helpPage, + private async Task UpdateFileAsync(HelpPageDto helpPage, int idCategory, string fileName, Stream fileStream, @@ -115,47 +150,11 @@ public class HelpPageService : IHelpPageService cancellationToken); } - /// - /// Получение справки по url страницы и id категории - /// - /// - /// - /// - /// - public Task GetOrDefaultByUrlPageAndIdCategoryAsync(string urlPage, - int idCategory, - CancellationToken cancellationToken) => - helpPageRepository.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage, - idCategory, - cancellationToken); - - public Task GetOrDefaultByIdAsync(int id, CancellationToken cancellationToken) => - helpPageRepository.GetOrDefaultAsync(id, - cancellationToken); - - /// - /// Получение файлового потока для файла справки - /// - /// - /// - /// - public Stream GetFileStream(HelpPageDto helpPage) - { - string filePath = fileStorageRepository.GetFilePath(directoryNameHelpPageFiles, - helpPage.IdCategory.ToString(), - helpPage.Id, - Path.GetExtension(helpPage.Name));; - - var fileStream = new FileStream(Path.GetFullPath(filePath), FileMode.Open); - - return fileStream; - } - private async Task SaveFileAsync(int idCategory, string fileName, Stream fileStream, int fileId, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken) { string filePath = fileStorageRepository.MakeFilePath(directoryNameHelpPageFiles, idCategory.ToString(), diff --git a/AsbCloudWebApi.Tests/ServicesTests/HelpPageServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/HelpPageServiceTest.cs index 3dbbb12f..076a5534 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/HelpPageServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/HelpPageServiceTest.cs @@ -5,10 +5,10 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using AsbCloudApp.Data; -using AsbCloudApp.Exceptions; using AsbCloudApp.Repositories; using AsbCloudApp.Services; using AsbCloudInfrastructure.Services; +using Microsoft.Extensions.Configuration; using Moq; using Xunit; @@ -16,7 +16,9 @@ namespace AsbCloudWebApi.Tests.ServicesTests; public class HelpPageServiceTest { - private const string directoryNameHelpPageFiles = "helpPages"; + private static Dictionary configSettings = new (){ + {"DirectoryNameHelpPageFiles", "helpPages"} + }; private static List HelpPages = new() { @@ -45,7 +47,7 @@ public class HelpPageServiceTest UrlPage = "test2" } }; - + private readonly Mock helpPageRepository = new(); private readonly Mock fileStorageRepository = new(); @@ -53,21 +55,36 @@ public class HelpPageServiceTest public HelpPageServiceTest() { + IConfiguration configuration = new ConfigurationBuilder() + .AddInMemoryCollection(configSettings) + .Build(); + helpPageService = new HelpPageService(helpPageRepository.Object, fileStorageRepository.Object, - directoryNameHelpPageFiles); + configuration); } [Fact] - public async Task CreateAsync_ShouldReturn_PositiveId() + public async Task AddOrUpdateAsync_ShouldReturn_NewHelpPage() { //arrange int idHelpPage = new Random().Next(1, 100); string urlPage = "test"; int idCategory = 20000; - string fullName = "test.pdf"; + string fileName = "test.pdf"; MemoryStream fileStream = new MemoryStream(Array.Empty()); + helpPageRepository.Setup(x => x.GetOrDefaultByUrlPageAndIdCategoryAsync(It.IsAny(), + It.IsAny(), It.IsAny())) + .Returns(() => + { + var helpPage = HelpPages.FirstOrDefault(x => + x.UrlPage == urlPage && + x.IdCategory == idCategory); + + return Task.FromResult(helpPage); + }); + helpPageRepository.Setup(x => x.InsertAsync(It.IsAny(), It.IsAny())) .Returns(() => Task.FromResult(idHelpPage)); @@ -77,9 +94,9 @@ public class HelpPageServiceTest It.IsAny())); //act - int result = await helpPageService.CreateAsync(urlPage, + int result = await helpPageService.AddOrUpdateAsync(urlPage, idCategory, - fullName, + fileName, fileStream, CancellationToken.None); @@ -87,110 +104,42 @@ public class HelpPageServiceTest Assert.True(result > 0); } - [Fact] - public async Task CreateAsync_ShouldReturn_ArgumentsInvalidException() - { - //arrange - string urlPage = "test"; - int idCategory = 20000; - string fullName = "test.pdf"; - MemoryStream fileStream = new MemoryStream(Array.Empty()); - bool isExistingHelpPage = true; - - helpPageRepository.Setup(x => x.IsCheckHelpPageWithUrlPageAndIdCategoryAsync(It.IsAny(), - It.IsAny(), - It.IsAny())) - .Returns(() => Task.FromResult(isExistingHelpPage)); - - //act - Task Result () => helpPageService.CreateAsync(urlPage, - idCategory, - fullName, - fileStream, - CancellationToken.None); - - //assert - await Assert.ThrowsAsync(Result); - } [Fact] public async Task UpdateAsync_ShouldReturn_UpdatedHelpPage() { //arrange - HelpPageDto helpPage = new() - { - Id = 123, - IdCategory = 134, - UrlPage = "test", - Name = "Справка.pdf", - Size = 54000 - }; - - int newIdCategory = 451; - string newFileName = "Новая справка.pdf"; + int idHelpPage = new Random().Next(1, 100); + string urlPage = "test"; + int newIdCategory = 20000; + string newFileName = "test.pdf"; MemoryStream newFileStream = new MemoryStream(Array.Empty()); - + HelpPageDto existingHelpPage = HelpPages.First(x => + x.UrlPage == urlPage && + x.IdCategory == newIdCategory); + + helpPageRepository.Setup(x => x.GetOrDefaultByUrlPageAndIdCategoryAsync(It.IsAny(), + It.IsAny(), It.IsAny())) + .Returns(() => Task.FromResult(existingHelpPage)!); + + helpPageRepository.Setup(x => x.InsertAsync(It.IsAny(), + It.IsAny())) + .Returns(() => Task.FromResult(idHelpPage)); + + fileStorageRepository.Setup(x => x.SaveFileAsync(It.IsAny(), + It.IsAny(), + It.IsAny())); + //act - await helpPageService.UpdateAsync(helpPage, + await helpPageService.AddOrUpdateAsync(urlPage, newIdCategory, newFileName, newFileStream, CancellationToken.None); - - //assert - Assert.Equal(newFileName, helpPage.Name); - Assert.Equal(newIdCategory, helpPage.IdCategory); - Assert.Equal(newFileStream.Length, helpPage.Size); - } - [Theory] - [InlineData(20000, "test")] - [InlineData(20000, "test1")] - public async Task GetOrDefaultByUrlPageAndIdCategoryAsync_ShouldReturn_HelpPageDto(int idCategory, - string urlPage) - { - //arrange - helpPageRepository.Setup(x => x.GetOrDefaultByUrlPageAndIdCategoryAsync(It.IsAny(), - It.IsAny(), It.IsAny())) - .Returns(() => - { - var helpPage = HelpPages.FirstOrDefault(x => - x.UrlPage == urlPage && - x.IdCategory == idCategory); - - return Task.FromResult(helpPage); - }); - - //act - var result = await helpPageService.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage, - idCategory, - CancellationToken.None); - //assert - Assert.NotNull(result); - } - - [Theory] - [InlineData(123)] - [InlineData(178)] - public async Task GetOrDefaultByIdAsync_ShouldReturn_HelpPageDto(int id) - { - //arrange - helpPageRepository.Setup(x => x.GetOrDefaultAsync(It.IsAny(), - It.IsAny())) - .Returns(() => - { - var helpPage = HelpPages.FirstOrDefault(x => - x.Id == id); - - return Task.FromResult(helpPage); - }); - - //act - var result = await helpPageService.GetOrDefaultByIdAsync(id, - CancellationToken.None); - - //assert - Assert.NotNull(result); + Assert.Equal(newFileName, existingHelpPage.Name); + Assert.Equal(newIdCategory, existingHelpPage.IdCategory); + Assert.Equal(newFileStream.Length, existingHelpPage.Size); } } \ No newline at end of file diff --git a/AsbCloudWebApi/Controllers/HelpPageController.cs b/AsbCloudWebApi/Controllers/HelpPageController.cs index d3bc0a48..9607d00e 100644 --- a/AsbCloudWebApi/Controllers/HelpPageController.cs +++ b/AsbCloudWebApi/Controllers/HelpPageController.cs @@ -5,9 +5,9 @@ using System.ComponentModel.DataAnnotations; using System.IO; using System.Threading; using System.Threading.Tasks; -using AsbCloudApp.Data; using AsbCloudApp.Repositories; using Microsoft.AspNetCore.Authorization; +using System.Net; namespace AsbCloudWebApi.Controllers; @@ -30,50 +30,37 @@ public class HelpPageController : ControllerBase } /// - /// Создание файла справки + /// Загрузка файла справки /// - /// Url страницы для которой предназначена эта справка - /// Id катагории файла - /// Загружаемый файл - /// Id созданной справки + /// Url страницы + /// Id категории файла + /// Файл справки + /// Токен для отмены задачи + /// [HttpPost] [Permission] - [Route("saveFile")] - [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] - public async Task CreateAsync(string urlPage, + [Route("upload")] + [ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)] + public async Task UploadAsync(string urlPage, int idCategory, - [Required] IFormFile file) + [Required] IFormFile file, + CancellationToken cancellationToken) { int? idUser = User.GetUserId(); if(!idUser.HasValue) return Forbid(); - if (!userRepository.HasPermission(idUser.Value, $"HelpPage.create")) + if (!userRepository.HasPermission(idUser.Value, $"HelpPage.edit")) 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, + int helpPageId = await helpPageService.AddOrUpdateAsync(urlPage, idCategory, file.FileName, fileStream, - CancellationToken.None); + cancellationToken); return Ok(helpPageId); } @@ -81,45 +68,29 @@ public class HelpPageController : ControllerBase /// /// Получение файла справки /// - /// Id справки - /// Файл + /// Url страницы + /// Id категории файла + /// Токен для отмены задачи + /// [HttpGet] - [Route("getById/{id}")] - [ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)] - public async Task GetFileAsync(int id) + [Route("get/{urlPage}/{idCategory}")] + [ProducesResponseType(typeof(PhysicalFileResult), (int)HttpStatusCode.OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task GetFileAsync(string urlPage, + int idCategory, + CancellationToken cancellationToken) { - var helpPage = await helpPageService.GetOrDefaultByIdAsync(id, - CancellationToken.None); + var file = await helpPageService.GetFileStreamAsync(urlPage, + idCategory, + cancellationToken); - if (helpPage is null) - return NotFound(); - - using var fileStream = helpPageService.GetFileStream(helpPage); + using var fileStream = file.stream; var memoryStream = new MemoryStream(); - await fileStream.CopyToAsync(memoryStream, - CancellationToken.None); + await fileStream.CopyToAsync(memoryStream, + cancellationToken); 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); + return File(memoryStream, "application/octet-stream", file.fileName); } } diff --git a/AsbCloudWebApi/Middlewares/SimplifyExceptionsMiddleware.cs b/AsbCloudWebApi/Middlewares/SimplifyExceptionsMiddleware.cs index 55e8c67c..89f51aa2 100644 --- a/AsbCloudWebApi/Middlewares/SimplifyExceptionsMiddleware.cs +++ b/AsbCloudWebApi/Middlewares/SimplifyExceptionsMiddleware.cs @@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Http; using System; using System.IO; using System.Threading.Tasks; -using AsbCloudApp.Exceptions.Interfaces; namespace AsbCloudWebApi.Middlewares { @@ -31,15 +30,6 @@ namespace AsbCloudWebApi.Middlewares var body = MakeJsonBody(ex); await context.Response.WriteAsync(body); } - catch (ArgumentsInvalidException ex) - { - Console.WriteLine($"ArgumentExceptions in {context.Request.Method}: {ex.Message}"); - context.Response.Clear(); - context.Response.StatusCode = 400; - context.Response.ContentType = "application/json"; - var body = MakeJsonBody(ex); - await context.Response.WriteAsync(body); - } catch (ForbidException ex) { Console.WriteLine($"ForbidException in {context.Request.Method}: {ex.Message}"); @@ -59,8 +49,7 @@ namespace AsbCloudWebApi.Middlewares } } - private static string MakeJsonBody(TException ex) - where TException: Exception, IHasValidation + private static string MakeJsonBody(ArgumentInvalidException ex) { object error = ex.ToValidationErrorObject(); var buffer = System.Text.Json.JsonSerializer.Serialize(error); diff --git a/AsbCloudWebApi/appsettings.json b/AsbCloudWebApi/appsettings.json index a1a7c6a5..683f7929 100644 --- a/AsbCloudWebApi/appsettings.json +++ b/AsbCloudWebApi/appsettings.json @@ -26,9 +26,7 @@ "companyName": "ООО \"Цифровое бурение\"", "supportMail": "support@digitaldrilling.ru" }, - "HelpPageOptions": { - "DirectoryNameHelpPageFiles": "helpPages" - }, + "DirectoryNameHelpPageFiles": "helpPages", "Urls": "http://0.0.0.0:5000" //;https://0.0.0.0:5001" //, // See https man: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/endpoints?view=aspnetcore-6.0 //"Kestrel": {