Merge branch 'feature/removing_unnecessary_files' into dev

This commit is contained in:
ngfrolov 2022-10-17 14:43:10 +05:00
commit 1f5867e4b3
14 changed files with 460 additions and 346 deletions

View File

@ -39,6 +39,11 @@ namespace AsbCloudApp.Data
/// </summary> /// </summary>
public long Size { get; set; } public long Size { get; set; }
/// <summary>
/// Помечен как удаленный
/// </summary>
public bool IsDeleted { get; set; }
/// <summary> /// <summary>
/// DTO автора /// DTO автора
/// </summary> /// </summary>

View File

@ -1,42 +1,33 @@
using AsbCloudApp.Data; using AsbCloudApp.Requests;
using AsbCloudApp.Data;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudApp.Repositories namespace AsbCloudApp.Repositories
{ {
#nullable enable
/// <summary> /// <summary>
/// Сервис доступа к файлам /// Сервис доступа к файлам
/// </summary> /// </summary>
public interface IFileRepository : ICrudService<FileInfoDto> public interface IFileRepository : ICrudService<FileInfoDto>
{ {
/// <summary> /// <summary>
/// Получить файлы определенной категории /// Получение файлов по скважине
/// </summary> /// </summary>
/// <param name="idWell"></param> /// <param name="request"></param>
/// <param name="idCategory"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<IEnumerable<FileInfoDto>> GetInfosByCategoryAsync(int idWell, int idCategory, CancellationToken token); Task<IEnumerable<FileInfoDto>> GetInfosAsync(FileRequest request, CancellationToken token);
/// <summary> /// <summary>
/// Получить список файлов в контейнере /// Получить список файлов в контейнере
/// </summary> /// </summary>
/// <param name="idWell"></param> /// <param name="request"></param>
/// <param name="idCategory"></param>
/// <param name="companyName"></param>
/// <param name="fileName"></param>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <param name="skip"></param>
/// <param name="take"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<PaginationContainer<FileInfoDto>> GetInfosAsync(int idWell, Task<PaginationContainer<FileInfoDto>> GetInfosPaginatedAsync(FileRequest request, CancellationToken token = default);
int idCategory, string companyName = default, string fileName = default, DateTime begin = default,
DateTime end = default, int skip = 0, int take = 32, CancellationToken token = default);
/// <summary> /// <summary>
/// Пометить файл как удаленный /// Пометить файл как удаленный
@ -87,12 +78,6 @@ namespace AsbCloudApp.Repositories
/// <returns></returns> /// <returns></returns>
Task<int> MarkFileMarkAsDeletedAsync(IEnumerable<int> idsMarks, CancellationToken token); Task<int> MarkFileMarkAsDeletedAsync(IEnumerable<int> idsMarks, CancellationToken token);
/// <summary>
/// Получение файлов по скважине
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<FileInfoDto>> GetInfosByWellIdAsync(int idWell, CancellationToken token);
} }
#nullable disable
} }

View File

@ -1,25 +1,23 @@
using System.IO; using AsbCloudApp.Data;
using System.Collections.Generic;
using System.IO;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudApp.Repositories namespace AsbCloudApp.Repositories
{ {
#nullable enable
/// <summary> /// <summary>
/// Репозиторий хранения фалов /// Репозиторий хранения фалов
/// </summary> /// </summary>
public interface IFileStorageRepository public interface IFileStorageRepository
{ {
/// <summary>
/// Директория хранения файлов
/// </summary>
string RootPath { get; }
/// <summary> /// <summary>
/// Получение длинны фала и проверка его наличия, если отсутствует падает исключение /// Получение длинны фала и проверка его наличия, если отсутствует падает исключение
/// </summary> /// </summary>
/// <param name="srcFilePath"></param> /// <param name="srcFilePath"></param>
/// <returns></returns> /// <returns></returns>
long GetLengthFile(string srcFilePath); long GetFileLength(string srcFilePath);
/// <summary> /// <summary>
/// Перемещение файла /// Перемещение файла
@ -31,21 +29,52 @@ namespace AsbCloudApp.Repositories
/// <summary> /// <summary>
/// Копирование файла /// Копирование файла
/// </summary> /// </summary>
/// <param name="filePathRec"></param>
/// <param name="fileStreamSrc"></param>
/// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task CopyFileAsync(string filePath, Stream fileStream, CancellationToken token); Task SaveFileAsync(string filePathRec, Stream fileStreamSrc, CancellationToken token);
/// <summary> /// <summary>
/// Удаление файла /// Удаление файла
/// </summary> /// </summary>
/// <param name="fileName"></param> /// <param name="filesName"></param>
void DeleteFile(string fileName); void DeleteFile(IEnumerable<string> filesName);
/// <summary> /// <summary>
/// Проверка наличия файла /// Удаление всех файлов с диска о которых нет информации в базе
/// </summary> /// </summary>
/// <param name="fullPath"></param> /// <param name="idWell"></param>
/// <param name="fileName"></param> /// <param name="idsFiles"></param>
int DeleteFilesNotInList(int idWell, IEnumerable<int> idsFiles);
/// <summary>
/// Вывод списка всех файлов из базы, для которых нет файла на диске
/// </summary>
/// <param name="idWell"></param>
/// <param name="files"></param>
/// <returns></returns> /// <returns></returns>
bool FileExists(string fullPath, string fileName); IEnumerable<FileInfoDto> GetListFilesNotDisc(IEnumerable<FileInfoDto> files);
/// <summary>
/// Получение пути к файлу
/// </summary>
/// <param name="idWell"></param>
/// <param name="idCategory"></param>
/// <param name="fileFullName"></param>
/// <param name="fileId"></param>
/// <returns></returns>
string MakeFilePath(int idWell, int idCategory, string fileFullName, int fileId);
/// <summary>
/// Получить путь для скачивания
/// </summary>
/// <param name="idWell"></param>
/// <param name="idCategory"></param>
/// <param name="idFile"></param>
/// <param name="dotExtention"></param>
/// <returns></returns>
string GetUrl(int idWell, int idCategory, int idFile, string dotExtention);
} }
#nullable disable
} }

View File

@ -0,0 +1,50 @@
using System;
using System.ComponentModel.DataAnnotations;
namespace AsbCloudApp.Requests
{
#nullable enable
/// <summary>
/// Параметры запроса для файлового сервиса
/// </summary>
public class FileRequest : RequestBase
{
/// <summary>
/// Идентификатор скважины
/// </summary>
[Required]
public int IdWell { get; set; }
/// <summary>
/// Идентификатор категории файла
/// </summary>
[Required]
public int? IdCategory { get; set; }
/// <summary>
/// Наименование компании
/// </summary>
public string? CompanyNamePart { get; set; }
/// <summary>
/// Имя файла
/// </summary>
public string? FileNamePart { get; set; }
/// <summary>
/// Дата начала периода
/// </summary>
public DateTime? Begin { get; set; }
/// <summary>
/// Дата окончания периода
/// </summary>
public DateTime? End { get; set; }
/// <summary>
/// Признак удаления
/// </summary>
public bool? IsDeleted { get; set; }
}
#nullable disable
}

View File

@ -1,6 +1,6 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
using System; using AsbCloudApp.Requests;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
@ -9,6 +9,7 @@ using System.Threading.Tasks;
namespace AsbCloudApp.Services namespace AsbCloudApp.Services
{ {
#nullable enable
/// <summary> /// <summary>
/// Сервис доступа к файлам /// Сервис доступа к файлам
/// </summary> /// </summary>
@ -38,12 +39,12 @@ namespace AsbCloudApp.Services
/// <param name="srcFilePath"></param> /// <param name="srcFilePath"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
public async Task<FileInfoDto> MoveAsync(int idWell, int? idUser, int idCategory, public async Task<FileInfoDto?> MoveAsync(int idWell, int? idUser, int idCategory,
string destinationFileName, string srcFilePath, CancellationToken token = default) string destinationFileName, string srcFilePath, CancellationToken token = default)
{ {
destinationFileName = Path.GetFileName(destinationFileName); destinationFileName = Path.GetFileName(destinationFileName);
srcFilePath = Path.GetFullPath(srcFilePath); srcFilePath = Path.GetFullPath(srcFilePath);
var fileSize = fileStorageRepository.GetLengthFile(srcFilePath); var fileSize = fileStorageRepository.GetFileLength(srcFilePath);
//save info to db //save info to db
var dto = new FileInfoDto { var dto = new FileInfoDto {
@ -56,10 +57,10 @@ namespace AsbCloudApp.Services
var fileId = await fileRepository.InsertAsync(dto, token) var fileId = await fileRepository.InsertAsync(dto, token)
.ConfigureAwait(false); .ConfigureAwait(false);
string filePath = MakeFilePath(idWell, idCategory, destinationFileName, fileId); string filePath = fileStorageRepository.MakeFilePath(idWell, idCategory, destinationFileName, fileId);
fileStorageRepository.MoveFile(srcFilePath, filePath); fileStorageRepository.MoveFile(srcFilePath, filePath);
return await GetInfoAsync(fileId, token); return await GetOrDefaultAsync(fileId, token);
} }
/// <summary> /// <summary>
@ -72,7 +73,7 @@ namespace AsbCloudApp.Services
/// <param name="fileStream"></param> /// <param name="fileStream"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
public async Task<FileInfoDto> SaveAsync(int idWell, int? idUser, int idCategory, public async Task<FileInfoDto?> SaveAsync(int idWell, int? idUser, int idCategory,
string fileFullName, Stream fileStream, CancellationToken token) string fileFullName, Stream fileStream, CancellationToken token)
{ {
//save info to db //save info to db
@ -82,37 +83,17 @@ namespace AsbCloudApp.Services
IdAuthor = idUser, IdAuthor = idUser,
IdCategory = idCategory, IdCategory = idCategory,
Name = Path.GetFileName(fileFullName), Name = Path.GetFileName(fileFullName),
Size = fileStream?.Length ?? 0 Size = fileStream.Length
}; };
var fileId = await fileRepository.InsertAsync(dto, token) var fileId = await fileRepository.InsertAsync(dto, token)
.ConfigureAwait(false); .ConfigureAwait(false);
//save stream to disk //save stream to disk
string filePath = MakeFilePath(idWell, idCategory, fileFullName, fileId); string filePath = fileStorageRepository.MakeFilePath(idWell, idCategory, fileFullName, fileId);
await fileStorageRepository.CopyFileAsync(filePath, fileStream, token); await fileStorageRepository.SaveFileAsync(filePath, fileStream, token);
return await GetInfoAsync(fileId, token); return await GetOrDefaultAsync(fileId, token);
}
/// <summary>
/// Инфо о файле
/// </summary>
/// <param name="idFile"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<FileInfoDto> GetInfoAsync(int idFile,
CancellationToken token)
{
var dto = await fileRepository.GetOrDefaultAsync(idFile, token).ConfigureAwait(false);
var ext = Path.GetExtension(dto.Name);
var relativePath = GetUrl(dto.IdWell, dto.IdCategory, dto.Id, ext);
var fullPath = Path.GetFullPath(relativePath);
fileStorageRepository.FileExists(fullPath, relativePath);
return dto;
} }
/// <summary> /// <summary>
@ -140,27 +121,12 @@ namespace AsbCloudApp.Services
if (files is null || !files.Any()) if (files is null || !files.Any())
return 0; return 0;
foreach (var file in files) var filesName = files.Select(x => GetUrl(x.IdWell, x.IdCategory, x.Id, Path.GetExtension(x.Name)));
{ fileStorageRepository.DeleteFile(filesName);
var fileName = GetUrl(file.IdWell, file.IdCategory, file.Id, Path.GetExtension(file.Name));
fileStorageRepository.DeleteFile(fileName);
}
return files.Any() ? 1 : 0; return files.Any() ? 1 : 0;
} }
/// <summary>
/// получить путь для скачивания
/// </summary>
/// <param name="idFile"></param>
/// <returns></returns>
public async Task<string> GetUrl(int idFile)
{
var fileInfo = await fileRepository.GetOrDefaultAsync(idFile, CancellationToken.None).ConfigureAwait(false);
return GetUrl(fileInfo.IdWell, fileInfo.IdCategory, fileInfo.Id, Path.GetExtension(fileInfo.Name));
}
/// <summary> /// <summary>
/// получить путь для скачивания /// получить путь для скачивания
/// </summary> /// </summary>
@ -178,7 +144,7 @@ namespace AsbCloudApp.Services
/// <param name="dotExtention"></param> /// <param name="dotExtention"></param>
/// <returns></returns> /// <returns></returns>
public string GetUrl(int idWell, int idCategory, int idFile, string dotExtention) => public string GetUrl(int idWell, int idCategory, int idFile, string dotExtention) =>
Path.Combine(fileStorageRepository.RootPath, idWell.ToString(), idCategory.ToString(), $"{idFile}{dotExtention}"); fileStorageRepository.GetUrl(idWell, idCategory, idFile, dotExtention);
/// <summary> /// <summary>
/// пометить метку файла как удаленную /// пометить метку файла как удаленную
@ -206,30 +172,28 @@ namespace AsbCloudApp.Services
var ext = Path.GetExtension(entity.Name); var ext = Path.GetExtension(entity.Name);
var relativePath = GetUrl(entity.IdWell, entity.IdCategory, entity.Id, ext); var relativePath = GetUrl(entity.IdWell, entity.IdCategory, entity.Id, ext);
var fullPath = Path.GetFullPath(relativePath); var fullPath = Path.GetFullPath(relativePath);
fileStorageRepository.FileExists(fullPath, relativePath);
} }
return result; return result;
} }
/// <summary> /// <summary>
/// Получить список файлов в контейнере /// Получить файлы определенной категории
/// </summary> /// </summary>
/// <param name="idWell"></param> /// <param name="request"></param>
/// <param name="idCategory"></param>
/// <param name="companyName"></param>
/// <param name="fileName"></param>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <param name="skip"></param>
/// <param name="take"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
public async Task<PaginationContainer<FileInfoDto>> GetInfosAsync(int idWell, public Task<IEnumerable<FileInfoDto>> GetInfosAsync(FileRequest request, CancellationToken token)
int idCategory, string companyName = default, string fileName = default, DateTime begin = default, => fileRepository.GetInfosAsync(request, token);
DateTime end = default, int skip = 0, int take = 32, CancellationToken token = default)
=> await fileRepository.GetInfosAsync(idWell, idCategory, companyName, fileName, begin, end, skip, take, token) /// <summary>
.ConfigureAwait(false); /// Получить список файлов в контейнере
/// </summary>
/// <param name="request"></param>
/// <param name="token"></param>
/// <returns></returns>
public Task<PaginationContainer<FileInfoDto>> GetInfosPaginatedAsync(FileRequest request, CancellationToken token)
=> fileRepository.GetInfosPaginatedAsync(request, token);
/// <summary> /// <summary>
/// Пометить файл как удаленный /// Пометить файл как удаленный
@ -237,9 +201,8 @@ namespace AsbCloudApp.Services
/// <param name="idFile"></param> /// <param name="idFile"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
public async Task<int> MarkAsDeletedAsync(int idFile, CancellationToken token = default) public Task<int> MarkAsDeletedAsync(int idFile, CancellationToken token = default)
=> await fileRepository.MarkAsDeletedAsync(idFile, token) => fileRepository.MarkAsDeletedAsync(idFile, token);
.ConfigureAwait(false);
/// <summary> /// <summary>
/// добавить метку на файл /// добавить метку на файл
@ -248,9 +211,8 @@ namespace AsbCloudApp.Services
/// <param name="idUser"></param> /// <param name="idUser"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
public async Task<int> CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token) public Task<int> CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token)
=> await fileRepository.CreateFileMarkAsync(fileMarkDto, idUser, token) => fileRepository.CreateFileMarkAsync(fileMarkDto, idUser, token);
.ConfigureAwait(false);
/// <summary> /// <summary>
/// Получить запись по id /// Получить запись по id
@ -258,9 +220,8 @@ namespace AsbCloudApp.Services
/// <param name="id"></param> /// <param name="id"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
public async Task<FileInfoDto> GetOrDefaultAsync(int id, CancellationToken token) public Task<FileInfoDto?> GetOrDefaultAsync(int id, CancellationToken token)
=> await fileRepository.GetOrDefaultAsync(id, token) => fileRepository.GetOrDefaultAsync(id, token);
.ConfigureAwait(false);
/// <summary> /// <summary>
/// получить инфо о файле по метке /// получить инфо о файле по метке
@ -268,45 +229,84 @@ namespace AsbCloudApp.Services
/// <param name="idMark"></param> /// <param name="idMark"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
public async Task<FileInfoDto> GetByMarkId(int idMark, CancellationToken token) public Task<FileInfoDto> GetByMarkId(int idMark, CancellationToken token)
=> await fileRepository.GetByMarkId(idMark, token) => fileRepository.GetByMarkId(idMark, token);
.ConfigureAwait(false);
/// <summary> /// <summary>
/// получить инфо о файле по метке /// получить инфо о файле по метке
/// </summary> /// </summary>
/// <param name="idMark"></param> /// <param name="idsMarks"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
public async Task<int> MarkFileMarkAsDeletedAsync(IEnumerable<int> idsMarks, CancellationToken token) public Task<int> MarkFileMarkAsDeletedAsync(IEnumerable<int> idsMarks, CancellationToken token)
=> await fileRepository.MarkFileMarkAsDeletedAsync(idsMarks, token) => fileRepository.MarkFileMarkAsDeletedAsync(idsMarks, token);
.ConfigureAwait(false);
/// <summary> /// <summary>
/// Получение файлов по скважине /// Удаление всех файлов по скважине помеченных как удаленные
/// </summary> /// </summary>
/// <param name="idWell"></param> /// <param name="idWell"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
public async Task<IEnumerable<FileInfoDto>> GetInfosByWellIdAsync(int idWell, CancellationToken token) public async Task<int> DeleteFilesFromDbMarkedDeletionByIdWell(int idWell, CancellationToken token)
=> await fileRepository.GetInfosByWellIdAsync(idWell, token)
.ConfigureAwait(false);
/// <summary>
/// Получить файлы определенной категории
/// </summary>
/// <param name="idWell"></param>
/// <param name="idCategory"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<IEnumerable<FileInfoDto>> GetInfosByCategoryAsync(int idWell, int idCategory, CancellationToken token)
=> await fileRepository.GetInfosByCategoryAsync(idWell, idCategory, token)
.ConfigureAwait(false);
private string MakeFilePath(int idWell, int idCategory, string fileFullName, int fileId)
{ {
return Path.Combine(fileStorageRepository.RootPath, $"{idWell}", var files = await fileRepository.GetInfosAsync(
$"{idCategory}", $"{fileId}" + $"{Path.GetExtension(fileFullName)}"); new FileRequest
{
IdWell = idWell,
IsDeleted = true
},
token);
var result = await DeleteAsync(files.Select(x => x.Id), token);
return result;
}
/// <summary>
/// Удаление всех файлов с диска о которых нет информации в базе
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>
public async Task<int> DeleteFilesNotExistStorage(int idWell, CancellationToken token)
{
var files = await fileRepository.GetInfosAsync(
new FileRequest
{
IdWell = idWell
},
token);
var result = await Task.FromResult(fileStorageRepository.DeleteFilesNotInList(idWell, files.Select(x => x.Id)));
return result;
}
/// <summary>
/// Вывод списка всех файлов из базы, для которых нет файла на диске
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<IEnumerable<FileInfoDto>> GetListFilesNotDisc(int idWell, CancellationToken token)
{
var files = await fileRepository.GetInfosAsync(
new FileRequest
{
IdWell = idWell
},
token);
var result = fileStorageRepository.GetListFilesNotDisc(files);
return result;
}
/// <summary>
/// Получить файловый поток по идентификатору файла
/// </summary>
/// <param name="fileInfo"></param>
/// <returns></returns>
public Stream GetFileStream(FileInfoDto fileInfo)
{
var relativePath = GetUrl(fileInfo);
var fileStream = new FileStream(Path.GetFullPath(relativePath), FileMode.Open);
return fileStream;
} }
} }
#nullable disable
} }

View File

@ -117,6 +117,17 @@ namespace AsbCloudDb
} }
return stat; return stat;
} }
public static IQueryable<T> SkipTake<T>(this IQueryable<T> query, int? skip, int? take)
{
if (skip > 0)
query = query.Skip((int)skip);
if (take > 0)
query = query.Take((int)take);
return query;
}
} }
interface IQueryStringFactory { } interface IQueryStringFactory { }

View File

@ -1,20 +1,27 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
using AsbCloudDb;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Wordprocessing;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Org.BouncyCastle.Asn1.Ocsp;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Repository namespace AsbCloudInfrastructure.Repository
{ {
#nullable enable
public class FileRepository : IFileRepository public class FileRepository : IFileRepository
{ {
private readonly IQueryable<AsbCloudDb.Model.FileInfo> dbSetConfigured; private readonly IQueryable<FileInfo> dbSetConfigured;
private readonly IAsbCloudDbContext db; private readonly IAsbCloudDbContext db;
public FileRepository(IAsbCloudDbContext db) public FileRepository(IAsbCloudDbContext db)
@ -29,10 +36,55 @@ namespace AsbCloudInfrastructure.Repository
.Include(f => f.Well); .Include(f => f.Well);
} }
public async Task<IEnumerable<FileInfoDto>> GetInfosByCategoryAsync(int idWell, int idCategory, CancellationToken token) private IQueryable<FileInfo> BuildQuery(FileRequest request)
{ {
var entities = await dbSetConfigured var query = dbSetConfigured
.Where(e => e.IdWell == idWell && e.IdCategory == idCategory && e.IsDeleted == false) .Where(e => e.IdWell == request.IdWell);
double timezoneOffsetHours = query.FirstOrDefault()
?.Well.Timezone.Hours ?? 5d;
if (request.IdCategory is not null)
query = query.Where(x => x.IdCategory == request.IdCategory);
if (request.IsDeleted is not null)
query = query.Where(x => x.IsDeleted == request.IsDeleted);
if (request.CompanyNamePart is not null)
query = query.Where(e => e.Author.Company.Caption.ToLower().Contains(request.CompanyNamePart.ToLower()));
if (request.FileNamePart is not null)
query = query.Where(e => e.Name.ToLower().Contains(request.FileNamePart.ToLower()));
if (request.Begin is not null)
{
var beginUtc = request.Begin.Value.ToUtcDateTimeOffset(timezoneOffsetHours);
query = query.Where(e => e.UploadDate >= beginUtc);
}
if (request.End is not null)
{
var endUtc = request.End.Value.ToUtcDateTimeOffset(timezoneOffsetHours);
query = query.Where(e => e.UploadDate <= endUtc);
}
if (request?.SortFields?.Any() == true)
{
query = query.SortBy(request.SortFields);
}
else
query = query
.OrderBy(o => o.UploadDate);
return query;
}
public async Task<IEnumerable<FileInfoDto>> GetInfosAsync(FileRequest request, CancellationToken token)
{
var query = BuildQuery(request);
var entities = await query
.SkipTake(request.Skip, request.Take)
.AsNoTracking() .AsNoTracking()
.ToListAsync(token) .ToListAsync(token)
.ConfigureAwait(false); .ConfigureAwait(false);
@ -41,76 +93,37 @@ namespace AsbCloudInfrastructure.Repository
return dtos; return dtos;
} }
public async Task<PaginationContainer<FileInfoDto>> GetInfosAsync(int idWell, public async Task<PaginationContainer<FileInfoDto>> GetInfosPaginatedAsync(FileRequest request, CancellationToken token = default)
int idCategory, string companyName = default, string fileName = default, DateTime begin = default,
DateTime end = default, int skip = 0, int take = 32, CancellationToken token = default)
{ {
var query = dbSetConfigured var skip = request.Skip ?? 0;
.Where(e => e.IdWell == idWell && var take = request.Take ?? 32;
e.IdCategory == idCategory &&
!e.IsDeleted);
if (!string.IsNullOrEmpty(companyName)) var query = BuildQuery(request);
query = query.Where(e => (e.Author == null) ||
(e.Author.Company == null) ||
e.Author.Company.Caption.Contains(companyName));
if (!string.IsNullOrEmpty(fileName)) var result = new PaginationContainer<FileInfoDto>()
query = query.Where(e => e.Name.ToLower().Contains(fileName.ToLower()));
var firstFile = await query.FirstOrDefaultAsync(token);
if (firstFile is null)
return new PaginationContainer<FileInfoDto>()
{
Skip = skip,
Take = take,
Count = 0,
};
var timezoneOffset = firstFile.Well.Timezone?.Hours ?? 5;
if (begin != default)
{
var beginUtc = begin.ToUtcDateTimeOffset(timezoneOffset);
query = query.Where(e => e.UploadDate >= beginUtc);
}
if (end != default)
{
var endUtc = end.ToUtcDateTimeOffset(timezoneOffset);
query = query.Where(e => e.UploadDate <= endUtc);
}
var count = await query.CountAsync(token).ConfigureAwait(false);
var result = new PaginationContainer<FileInfoDto>(count)
{ {
Skip = skip, Skip = skip,
Take = take, Take = take,
Count = count, Count = await query.CountAsync(token),
}; };
if (count <= skip) if (result.Count == 0)
return result; return result;
query = query.OrderBy(e => e.UploadDate);
if (skip > 0)
query = query.Skip(skip);
query = query.Take(take);
var entities = await query var entities = await query
.Take(take).AsNoTracking().ToListAsync(token) .SkipTake(skip, take)
.AsNoTracking()
.ToListAsync(token)
.ConfigureAwait(false); .ConfigureAwait(false);
var dtos = entities.Select(e => Convert(e, timezoneOffset)); result.Items = entities.Select(e => Convert(e)).ToList();
result.Items.AddRange(dtos);
return result; return result;
} }
public async Task<IEnumerable<FileInfoDto>> GetInfoByIdsAsync(IEnumerable<int> idsFile, CancellationToken token) public async Task<IEnumerable<FileInfoDto>> GetInfoByIdsAsync(IEnumerable<int> idsFile, CancellationToken token)
{ {
var result = new List<FileInfoDto>(); var result = Enumerable.Empty<FileInfoDto>();
var entities = await dbSetConfigured var entities = await dbSetConfigured
.AsNoTracking() .AsNoTracking()
@ -118,14 +131,8 @@ namespace AsbCloudInfrastructure.Repository
.ToListAsync(token) .ToListAsync(token)
.ConfigureAwait(false); .ConfigureAwait(false);
foreach (var entity in entities) if (entities is not null)
{ result = entities.Select(entity => Convert(entity));
if (entity is null)
{
throw new FileNotFoundException($"fileId:{entity.Id} not found");
}
result.Add(Convert(entity));
}
return result; return result;
} }
@ -163,7 +170,7 @@ namespace AsbCloudInfrastructure.Repository
.FirstOrDefaultAsync(f => f.FileMarks.Any(m => m.Id == idMark), token) .FirstOrDefaultAsync(f => f.FileMarks.Any(m => m.Id == idMark), token)
.ConfigureAwait(false); .ConfigureAwait(false);
FileInfoDto dto = Convert(entity); FileInfoDto dto = Convert(entity!);
return dto; return dto;
} }
@ -201,44 +208,13 @@ namespace AsbCloudInfrastructure.Repository
return await db.SaveChangesAsync(token); return await db.SaveChangesAsync(token);
} }
public async Task<IEnumerable<FileInfoDto>> GetInfosByWellIdAsync(int idWell, CancellationToken token)
{
var entities = await dbSetConfigured
.Where(e => e.IdWell == idWell && e.IsDeleted == false)
.AsNoTracking()
.ToListAsync(token)
.ConfigureAwait(false);
var dtos = entities.Select(e => Convert(e));
return dtos;
}
private static FileInfoDto Convert(AsbCloudDb.Model.FileInfo entity)
{
var timezoneOffset = entity.Well.Timezone?.Hours ?? 5;
return Convert(entity, timezoneOffset);
}
private static FileInfoDto Convert(AsbCloudDb.Model.FileInfo entity, double timezoneOffset)
{
var dto = entity.Adapt<FileInfoDto>();
dto.UploadDate = entity.UploadDate.ToRemoteDateTime(timezoneOffset);
dto.FileMarks = entity.FileMarks.Select(m =>
{
var mark = m.Adapt<FileMarkDto>();
mark.DateCreated = m.DateCreated.ToRemoteDateTime(timezoneOffset);
return mark;
});
return dto;
}
public async Task<IEnumerable<FileInfoDto>> GetAllAsync(CancellationToken token) public async Task<IEnumerable<FileInfoDto>> GetAllAsync(CancellationToken token)
=> await dbSetConfigured.AsNoTracking() => await dbSetConfigured.AsNoTracking()
.Select(x => Convert(x)) .Select(x => Convert(x))
.ToListAsync(token) .ToListAsync(token)
.ConfigureAwait(false); .ConfigureAwait(false);
public async Task<FileInfoDto> GetOrDefaultAsync(int id, CancellationToken token) public async Task<FileInfoDto?> GetOrDefaultAsync(int id, CancellationToken token)
{ {
var entity = await dbSetConfigured var entity = await dbSetConfigured
.AsNoTracking() .AsNoTracking()
@ -246,24 +222,20 @@ namespace AsbCloudInfrastructure.Repository
.ConfigureAwait(false); .ConfigureAwait(false);
if (entity is null) if (entity is null)
{ return null;
throw new FileNotFoundException($"fileId:{id} not found");
}
var dto = Convert(entity); var dto = Convert(entity);
return dto; return dto;
} }
public FileInfoDto GetOrDefault(int id) public FileInfoDto? GetOrDefault(int id)
{ {
var entity = dbSetConfigured var entity = dbSetConfigured
.AsNoTracking() .AsNoTracking()
.FirstOrDefault(f => f.Id == id); .FirstOrDefault(f => f.Id == id);
if (entity is null) if (entity is null)
{ return null;
throw new FileNotFoundException($"fileId:{id} not found");
}
var dto = Convert(entity); var dto = Convert(entity);
return dto; return dto;
@ -271,7 +243,7 @@ namespace AsbCloudInfrastructure.Repository
public async Task<int> InsertAsync(FileInfoDto newItem, CancellationToken token) public async Task<int> InsertAsync(FileInfoDto newItem, CancellationToken token)
{ {
var fileInfo = new AsbCloudDb.Model.FileInfo() var fileInfo = new FileInfo()
{ {
IdWell = newItem.IdWell, IdWell = newItem.IdWell,
IdAuthor = newItem.IdAuthor, IdAuthor = newItem.IdAuthor,
@ -301,5 +273,25 @@ namespace AsbCloudInfrastructure.Repository
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
private static FileInfoDto Convert(FileInfo entity)
{
var timezoneOffset = entity.Well.Timezone?.Hours ?? 5;
return Convert(entity, timezoneOffset);
}
private static FileInfoDto Convert(FileInfo entity, double timezoneOffset)
{
var dto = entity.Adapt<FileInfoDto>();
dto.UploadDate = entity.UploadDate.ToRemoteDateTime(timezoneOffset);
dto.FileMarks = entity.FileMarks.Select(m =>
{
var mark = m.Adapt<FileMarkDto>();
mark.DateCreated = m.DateCreated.ToRemoteDateTime(timezoneOffset);
return mark;
});
return dto;
}
} }
#nullable disable
} }

View File

@ -1,38 +1,43 @@
using AsbCloudApp.Exceptions; using AsbCloudApp.Data;
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Repository namespace AsbCloudInfrastructure.Repository
{ {
#nullable enable
public class FileStorageRepository : IFileStorageRepository public class FileStorageRepository : IFileStorageRepository
{ {
public string RootPath { get; private set; } /// <summary>
/// Директория хранения файлов
/// </summary>
private readonly string RootPath = "files";
public FileStorageRepository() public FileStorageRepository()
{ {
RootPath = "files";
} }
public async Task CopyFileAsync(string filePath, Stream fileStream, CancellationToken token) public async Task SaveFileAsync(string filePathRec, Stream fileStreamSrc, CancellationToken token)
{ {
CreateDirectory(filePath); CreateDirectory(filePathRec);
using var newfileStream = new FileStream(filePath, FileMode.Create); using var newfileStream = new FileStream(filePathRec, FileMode.Create);
await fileStream.CopyToAsync(newfileStream, token).ConfigureAwait(false); await fileStreamSrc.CopyToAsync(newfileStream, token).ConfigureAwait(false);
} }
public void DeleteFile(string fileName) public void DeleteFile(IEnumerable<string> filesName)
{ {
if (File.Exists(fileName)) foreach (var fileName in filesName)
File.Delete(fileName); {
if (File.Exists(fileName))
File.Delete(fileName);
}
} }
public long GetLengthFile(string srcFilePath) public long GetFileLength(string srcFilePath)
{ {
if (!File.Exists(srcFilePath))
throw new ArgumentInvalidException($"file {srcFilePath} doesn't exist", nameof(srcFilePath));
var sysFileInfo = new FileInfo(srcFilePath); var sysFileInfo = new FileInfo(srcFilePath);
return sysFileInfo.Length; return sysFileInfo.Length;
} }
@ -43,17 +48,74 @@ namespace AsbCloudInfrastructure.Repository
File.Move(srcFilePath, filePath); File.Move(srcFilePath, filePath);
} }
public bool FileExists(string fullPath, string fileName) public string MakeFilePath(int idWell, int idCategory, string fileFullName, int fileId)
{ {
if (!File.Exists(fullPath)) return Path.Combine(RootPath, $"{idWell}",
throw new FileNotFoundException("not found", fileName); $"{idCategory}", $"{fileId}" + $"{Path.GetExtension(fileFullName)}");
return true;
} }
private void CreateDirectory(string filePath) public int DeleteFilesNotInList(int idWell, IEnumerable<int> idsFilesList)
{ {
Directory.CreateDirectory(Path.GetDirectoryName(filePath)); var allFilesPath = GetFilesPath(idWell);
var result = 0;
foreach (var filePath in allFilesPath)
{
if (int.TryParse(Path.GetFileNameWithoutExtension(filePath), out int idFile)
|| !idsFilesList.Any(x => x == idFile))
{
File.Delete(filePath);
result++;
}
}
return result;
}
public IEnumerable<FileInfoDto> GetListFilesNotDisc(IEnumerable<FileInfoDto> files)
{
var resutl = new List<FileInfoDto>();
var groupFiles = files.GroupBy(x => x.IdWell);
foreach (var itemGroupFiles in groupFiles)
{
var idsFilesStorage = GetIdsFiles(itemGroupFiles.Key);
foreach (var file in files)
{
if (!idsFilesStorage.Any(x => x == file.Id))
resutl.Add(file);
}
}
return resutl;
}
public string GetUrl(int idWell, int idCategory, int idFile, string dotExtention) =>
Path.Combine(RootPath, idWell.ToString(), idCategory.ToString(), $"{idFile}{dotExtention}");
private IEnumerable<int> GetIdsFiles(int idWell)
{
var result = new List<int>();
var allFilesPath = GetFilesPath(idWell);
foreach (var filePath in allFilesPath)
if(int.TryParse(Path.GetFileNameWithoutExtension(filePath), out int idFile))
result.Add(idFile);
return result;
}
private IEnumerable<string> GetFilesPath(int idWell)
{
var path = Path.Combine(RootPath, $"{idWell}");
return Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
}
private static void CreateDirectory(string filePath)
{
var directoryName = Path.GetDirectoryName(filePath)!;
Directory.CreateDirectory(directoryName);
} }
} }
#nullable disable
} }

View File

@ -282,7 +282,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
fileMarkDto.IdMarkType != idMarkTypeReject) fileMarkDto.IdMarkType != idMarkTypeReject)
throw new ArgumentInvalidException($"В этом методе допустимы только отметки о принятии или отклонении.", nameof(fileMarkDto)); throw new ArgumentInvalidException($"В этом методе допустимы только отметки о принятии или отклонении.", nameof(fileMarkDto));
var fileInfo = await fileService.GetInfoAsync(fileMarkDto.IdFile, token) var fileInfo = await fileService.GetOrDefaultAsync(fileMarkDto.IdFile, token)
.ConfigureAwait(false); .ConfigureAwait(false);
if (fileInfo is null) if (fileInfo is null)
@ -357,7 +357,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
private async Task NotifyPublisherOnFullAccepAsync(FileMarkDto fileMark, CancellationToken token) private async Task NotifyPublisherOnFullAccepAsync(FileMarkDto fileMark, CancellationToken token)
{ {
var file = await fileService.GetInfoAsync(fileMark.IdFile, token); var file = await fileService.GetOrDefaultAsync(fileMark.IdFile, token);
var well = await wellService.GetOrDefaultAsync(file.IdWell, token); var well = await wellService.GetOrDefaultAsync(file.IdWell, token);
var user = file.Author; var user = file.Author;
var factory = new DrillingMailBodyFactory(configuration); var factory = new DrillingMailBodyFactory(configuration);
@ -369,7 +369,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
private async Task NotifyPublisherOnRejectAsync(FileMarkDto fileMark, CancellationToken token) private async Task NotifyPublisherOnRejectAsync(FileMarkDto fileMark, CancellationToken token)
{ {
var file = await fileService.GetInfoAsync(fileMark.IdFile, token); var file = await fileService.GetOrDefaultAsync(fileMark.IdFile, token);
var well = await wellService.GetOrDefaultAsync(file.IdWell, token); var well = await wellService.GetOrDefaultAsync(file.IdWell, token);
var user = file.Author; var user = file.Author;
var factory = new DrillingMailBodyFactory(configuration); var factory = new DrillingMailBodyFactory(configuration);
@ -473,7 +473,6 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
var well = await wellService.GetOrDefaultAsync(idWell, token); var well = await wellService.GetOrDefaultAsync(idWell, token);
var resultFileName = $"Программа бурения {well.Cluster} {well.Caption}.xlsx"; var resultFileName = $"Программа бурения {well.Cluster} {well.Caption}.xlsx";
var tempResultFilePath = Path.Combine(Path.GetTempPath(), "drillingProgram", resultFileName); var tempResultFilePath = Path.Combine(Path.GetTempPath(), "drillingProgram", resultFileName);
var mailService = new EmailService(backgroundWorker, configuration);
async Task funcProgramMake(string id, CancellationToken token) async Task funcProgramMake(string id, CancellationToken token)
{ {
var contextOptions = new DbContextOptionsBuilder<AsbCloudDbContext>() var contextOptions = new DbContextOptionsBuilder<AsbCloudDbContext>()

View File

@ -1,5 +1,6 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Exceptions; using AsbCloudApp.Exceptions;
using AsbCloudApp.Requests;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository; using AsbCloudInfrastructure.Repository;
@ -96,7 +97,7 @@ namespace AsbCloudInfrastructure.Services
.Select(g => g.Key); .Select(g => g.Key);
var files = (await fileService var files = (await fileService
.GetInfosByWellIdAsync(idWell, token) .GetInfosAsync(new FileRequest { IdWell = idWell}, token)
.ConfigureAwait(false)) .ConfigureAwait(false))
.Where(f => categoriesIds.Contains(f.IdCategory)) .Where(f => categoriesIds.Contains(f.IdCategory))
.ToArray(); .ToArray();
@ -162,7 +163,12 @@ namespace AsbCloudInfrastructure.Services
public async Task<WellFinalDocumentsHistoryDto> GetFilesHistoryByIdCategory(int idWell, int idCategory, CancellationToken token) public async Task<WellFinalDocumentsHistoryDto> GetFilesHistoryByIdCategory(int idWell, int idCategory, CancellationToken token)
{ {
var files = await fileService.GetInfosByCategoryAsync(idWell, idCategory, token).ConfigureAwait(false); var request = new FileRequest
{
IdWell = idWell,
IdCategory = idCategory,
};
var files = await fileService.GetInfosAsync(request, token).ConfigureAwait(false);
return new WellFinalDocumentsHistoryDto { return new WellFinalDocumentsHistoryDto {
IdWell = idWell, IdWell = idWell,

View File

@ -0,0 +1,9 @@
# Создание репозитория для сервися
1. Создать интерфейс репозитория в AsbCloudApp.Services
2. Создать репозиторий в AsbCloudInfrastructure.Repository, наследоваться от созданного интерфейса, в нем добавить работу с БД
3. Добавить репозиторий в AsbCloudInfrastructure.DependencyInjection
4. Добавить в конструктор сервиса новый репозиторий и использовать его методы
5. Перенести сервис из AsbCloudInfrastructure.Services в AsbCloudApp.Services
6. Добавить или поправить тесты на изменяемый сервис используя AsbCloudWebApi.Tests.RepositoryFactory
7. В тестах сделать мок данных для репозитория

View File

@ -220,7 +220,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
{ {
ConfigureNotApproved(); ConfigureNotApproved();
fileServiceMock fileServiceMock
.Setup(s => s.GetInfoAsync(It.IsAny<int>(), It.IsAny<CancellationToken>())) .Setup(s => s.GetOrDefaultAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(file1002.Adapt<FileInfoDto>())); .Returns(Task.FromResult(file1002.Adapt<FileInfoDto>()));
fileServiceMock fileServiceMock
@ -251,7 +251,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
{ {
ConfigureNotApproved(); ConfigureNotApproved();
fileServiceMock fileServiceMock
.Setup(s => s.GetInfoAsync(It.IsAny<int>(), It.IsAny<CancellationToken>())) .Setup(s => s.GetOrDefaultAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(file1002.Adapt<FileInfoDto>())); .Returns(Task.FromResult(file1002.Adapt<FileInfoDto>()));
fileServiceMock fileServiceMock

View File

@ -1,21 +1,15 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository;
using AsbCloudInfrastructure.Services;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using Moq; using Moq;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using Xunit;
using static AsbCloudWebApi.Tests.TestHelpter;
namespace AsbCloudWebApi.Tests.ServicesTests namespace AsbCloudWebApi.Tests.ServicesTests
{ {
@ -115,15 +109,9 @@ namespace AsbCloudWebApi.Tests.ServicesTests
return Task.FromResult(result); return Task.FromResult(result);
}); });
repositoryMock.Setup(x => x.GetInfosByWellIdAsync(It.IsAny<int>(), It.IsAny<CancellationToken>())) repositoryMock.Setup(x => x.GetInfosAsync(It.IsAny<FileRequest>(), It.IsAny<CancellationToken>()))
.Returns((int idWell, CancellationToken token) => { .Returns((FileRequest request, CancellationToken token) => {
var data = Files.Where(x => x.IdWell == idWell); var data = Files.Where(x => x.IdWell == request.IdWell);
return Task.FromResult(data);
});
repositoryMock.Setup(x => x.GetInfosByCategoryAsync(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns((int idWell, int idCategory, CancellationToken token) => {
var data = Files.Where(x => x.IdWell == idWell && x.IdCategory == idCategory);
return Task.FromResult(data); return Task.FromResult(data);
}); });
@ -139,8 +127,10 @@ namespace AsbCloudWebApi.Tests.ServicesTests
}); });
var storageRepositoryMock = new Mock<IFileStorageRepository>(); var storageRepositoryMock = new Mock<IFileStorageRepository>();
storageRepositoryMock.Setup(x => x.GetUrl(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<string>()))
storageRepositoryMock.Setup(x => x.RootPath).Returns("files"); .Returns((int idWell, int idCategory, int idFile, string dotExtention) => {
return Path.Combine("files", idWell.ToString(), idCategory.ToString(), $"{idFile}{dotExtention}");
});
fileService = new FileService(repositoryMock.Object, storageRepositoryMock.Object); fileService = new FileService(repositoryMock.Object, storageRepositoryMock.Object);
} }
@ -153,9 +143,9 @@ namespace AsbCloudWebApi.Tests.ServicesTests
} }
[Fact] [Fact]
public async Task GetInfoAsync_returns_FileInfo() public async Task GetOrDefaultAsync_returns_FileInfo()
{ {
var data = await fileService.GetInfoAsync(1742, CancellationToken.None); var data = await fileService.GetOrDefaultAsync(1742, CancellationToken.None);
Assert.NotNull(data); Assert.NotNull(data);
} }
@ -195,20 +185,6 @@ namespace AsbCloudWebApi.Tests.ServicesTests
Assert.True(result > 0); Assert.True(result > 0);
} }
[Fact]
public async Task GetInfosByWellIdAsync_returns_FileInfo()
{
var data = await fileService.GetInfosByWellIdAsync(90, CancellationToken.None);
Assert.NotNull(data);
}
[Fact]
public async Task GetInfosByCategoryAsync_returns_FileInfo()
{
var data = await fileService.GetInfosByCategoryAsync(90, 10040, CancellationToken.None);
Assert.NotNull(data);
}
[Fact] [Fact]
public async Task CreateFileMarkAsync() public async Task CreateFileMarkAsync()
{ {

View File

@ -1,17 +1,17 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Requests;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsbCloudDb.Model;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
{ {
#nullable enable
/// <summary> /// <summary>
/// Хранение файлов /// Хранение файлов
/// </summary> /// </summary>
@ -70,38 +70,27 @@ namespace AsbCloudWebApi.Controllers
/// <summary> /// <summary>
/// Возвращает информацию о файлах для скважины в выбраной категории /// Возвращает информацию о файлах для скважины в выбраной категории
/// </summary> /// </summary>
/// <param name="idWell">id скважины</param> /// <param name="request"> </param>
/// <param name="idCategory">id категории файла</param>
/// <param name="companyName">id компаний для фильтрации возвращаемых файлов</param>
/// <param name="fileName">часть имени файла для поиска</param>
/// <param name="begin">дата начала</param>
/// <param name="end">дата окончания</param>
/// <param name="skip">для пагинации кол-во записей пропустить</param>
/// <param name="take">для пагинации кол-во записей взять </param>
/// <param name="token"> Токен отмены задачи </param> /// <param name="token"> Токен отмены задачи </param>
/// <returns>Список информации о файлах в этой категории</returns> /// <returns>Список информации о файлах в этой категории</returns>
[HttpGet] [HttpGet]
[Route("/api/files")]
[Permission] [Permission]
[ProducesResponseType(typeof(PaginationContainer<FileInfoDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(PaginationContainer<FileInfoDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetFilesInfoAsync( public async Task<IActionResult> GetFilesInfoAsync(
[FromRoute] int idWell, [FromQuery] FileRequest request,
int idCategory = default,
string companyName = default,
string fileName = default,
DateTime begin = default,
DateTime end = default,
int skip = 0,
int take = 32,
CancellationToken token = default) CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, if (request.IdCategory is null || idCompany is null)
idWell, token).ConfigureAwait(false))
return Forbid(); return Forbid();
var filesInfo = await fileService.GetInfosAsync(idWell, idCategory, if (!await wellService.IsCompanyInvolvedInWellAsync(idCompany.Value,
companyName, fileName, begin, end, skip, take, token).ConfigureAwait(false); request.IdWell, token).ConfigureAwait(false))
return Forbid();
var filesInfo = await fileService.GetInfosPaginatedAsync(request, token).ConfigureAwait(false);
return Ok(filesInfo); return Ok(filesInfo);
} }
@ -110,36 +99,33 @@ namespace AsbCloudWebApi.Controllers
/// Возвращает файл с диска на сервере /// Возвращает файл с диска на сервере
/// </summary> /// </summary>
/// <param name="idWell">id скважины</param> /// <param name="idWell">id скважины</param>
/// <param name="fileId">id запрашиваемого файла</param> /// <param name="idFile">id запрашиваемого файла</param>
/// <param name="token"> Токен отмены задачи </param> /// <param name="token"> Токен отмены задачи </param>
/// <returns>Запрашиваемый файл</returns> /// <returns>Запрашиваемый файл</returns>
[HttpGet] [HttpGet]
[Route("{fileId}")] [Route("{idFile}")]
[Permission] [Permission]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetFileAsync([FromRoute] int idWell, public async Task<IActionResult> GetFileAsync([FromRoute] int idWell,
int fileId, CancellationToken token = default) int idFile, CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null) if (idCompany is null)
return Forbid(); return Forbid();
var fileInfo = await fileService.GetOrDefaultAsync(idFile, token);
if (fileInfo is null)
return NotFound(idFile);
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false)) fileInfo.IdWell, token).ConfigureAwait(false))
return Forbid(); return Forbid();
try var fileStream = fileService.GetFileStream(fileInfo);
{
var fileInfo = await fileService.GetInfoAsync(fileId, token);
var relativePath = fileService.GetUrl(fileInfo); return File(fileStream, "application/octet-stream", fileInfo.Name);
return PhysicalFile(Path.GetFullPath(relativePath), "application/octet-stream", fileInfo.Name);
}
catch (FileNotFoundException ex)
{
return NotFound(ex.FileName);
}
} }
/// <summary> /// <summary>
@ -161,13 +147,16 @@ namespace AsbCloudWebApi.Controllers
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, if (idUser is null || idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false)) idWell, token).ConfigureAwait(false))
return Forbid(); return Forbid();
var file = await fileService.GetInfoAsync((int)idFile, token); var fileInfo = await fileService.GetOrDefaultAsync(idFile, token);
if (!userService.HasPermission((int)idUser, $"File.edit{file.IdCategory}")) if (fileInfo is null)
return NotFound(idFile);
if (!userService.HasPermission((int)idUser, $"File.edit{fileInfo?.IdCategory}"))
return Forbid(); return Forbid();
var result = await fileService.MarkAsDeletedAsync(idFile, token); var result = await fileService.MarkAsDeletedAsync(idFile, token);
@ -254,4 +243,5 @@ namespace AsbCloudWebApi.Controllers
} }
} }
} }
#nullable disable
} }