##6539681 Файловый репозиторий

This commit is contained in:
ai.astrakhantsev 2022-09-28 10:46:12 +05:00
parent 8a7e2872ee
commit 863749cfe1
9 changed files with 476 additions and 336 deletions

View File

@ -31,23 +31,6 @@ namespace AsbCloudApp.Services
/// <returns></returns> /// <returns></returns>
Task<FileInfoDto> SaveAsync(int idWell, int? idUser, int idCategory, string fileFullName, Stream fileStream, CancellationToken token = default); Task<FileInfoDto> SaveAsync(int idWell, int? idUser, int idCategory, string fileFullName, Stream fileStream, CancellationToken token = default);
/// <summary>
/// Получить список файлов в контейнере
/// </summary>
/// <param name="idWell"></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>
/// <returns></returns>
Task<PaginationContainer<FileInfoDto>> GetInfosAsync(int idWell,
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>
/// Инфо о файле /// Инфо о файле
/// </summary> /// </summary>
@ -57,24 +40,6 @@ namespace AsbCloudApp.Services
Task<FileInfoDto> GetInfoAsync(int idFile, Task<FileInfoDto> GetInfoAsync(int idFile,
CancellationToken token); CancellationToken token);
/// <summary>
/// Пометить файл как удаленный
/// </summary>
/// <param name="idFile"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> MarkAsDeletedAsync(int idFile,
CancellationToken token = default);
/// <summary>
/// Получить файлы определенной категории
/// </summary>
/// <param name="idWell"></param>
/// <param name="idCategory"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<FileInfoDto>> GetInfosByCategoryAsync(int idWell, int idCategory, CancellationToken token = default);
/// <summary> /// <summary>
/// удалить файл /// удалить файл
/// </summary> /// </summary>
@ -103,7 +68,7 @@ namespace AsbCloudApp.Services
/// </summary> /// </summary>
/// <param name="idFile"></param> /// <param name="idFile"></param>
/// <returns></returns> /// <returns></returns>
string GetUrl(int idFile); Task<string> GetUrl(int idFile);
/// <summary> /// <summary>
/// получить путь для скачивания /// получить путь для скачивания
@ -115,15 +80,6 @@ namespace AsbCloudApp.Services
/// <returns></returns> /// <returns></returns>
string GetUrl(int idWell, int idCategory, int idFile, string dotExtention); string GetUrl(int idWell, int idCategory, int idFile, string dotExtention);
/// <summary>
/// добавить метку на файл
/// </summary>
/// <param name="fileMarkDto"></param>
/// <param name="idUser"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token);
/// <summary> /// <summary>
/// пометить метку файла как удаленную /// пометить метку файла как удаленную
/// </summary> /// </summary>
@ -143,22 +99,6 @@ namespace AsbCloudApp.Services
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<FileInfoDto> MoveAsync(int idWell, int? idUser, int idCategory, string destinationFileName, string srcFileFullName, CancellationToken token = default); Task<FileInfoDto> MoveAsync(int idWell, int? idUser, int idCategory, string destinationFileName, string srcFileFullName, CancellationToken token = default);
/// <summary>
/// получить инфо о файле по метке
/// </summary>
/// <param name="idMark"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<FileInfoDto> GetByMarkId(int idMark, CancellationToken token);
/// <summary>
/// пометить метки файлов как удаленные
/// </summary>
/// <param name="idsMarks"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> MarkFileMarkAsDeletedAsync(IEnumerable<int> idsMarks, CancellationToken token);
/// <summary> /// <summary>
/// Инфо о файле /// Инфо о файле
@ -166,14 +106,6 @@ namespace AsbCloudApp.Services
/// <param name="idsFile"></param> /// <param name="idsFile"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<List<FileInfoDto>> GetInfoByIdsAsync(List<int> idsFile, CancellationToken token); Task<IEnumerable<FileInfoDto>> GetInfoByIdsAsync(IEnumerable<int> idsFile, CancellationToken token);
/// <summary>
/// Получение файлов по скважине
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<FileInfoDto>> GetInfosByWellIdAsync(int idWell, CancellationToken token);
} }
} }

View File

@ -106,6 +106,7 @@ namespace AsbCloudInfrastructure
services.AddTransient<IDrillParamsService, DrillParamsService>(); services.AddTransient<IDrillParamsService, DrillParamsService>();
services.AddTransient<IEventService, EventService>(); services.AddTransient<IEventService, EventService>();
services.AddTransient<IFileService, FileService>(); services.AddTransient<IFileService, FileService>();
services.AddTransient<IFileRepository, FileRepository>();
services.AddTransient<IMeasureService, MeasureService>(); services.AddTransient<IMeasureService, MeasureService>();
services.AddTransient<IMessageService, MessageService>(); services.AddTransient<IMessageService, MessageService>();
services.AddTransient<IOperationsStatService, OperationsStatService>(); services.AddTransient<IOperationsStatService, OperationsStatService>();

View File

@ -0,0 +1,275 @@
using AsbCloudApp.Data;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Repository
{
public class FileRepository : IFileRepository
{
private readonly IQueryable<AsbCloudDb.Model.FileInfo> dbSetConfigured;
private readonly IAsbCloudDbContext db;
public FileRepository(IAsbCloudDbContext db)
{
this.db = db;
this.dbSetConfigured = db.Files
.Include(f => f.Author)
.ThenInclude(u => u.Company)
.ThenInclude(c => c.CompanyType)
.Include(f => f.FileMarks)
.ThenInclude(m => m.User)
.Include(f => f.Well);
}
public async Task<int> AddAsync(int idWell, int? idUser, int idCategory,
string destinationFileName, long fileSize, CancellationToken token = default)
{
var fileInfo = new AsbCloudDb.Model.FileInfo()
{
IdWell = idWell,
IdAuthor = idUser,
IdCategory = idCategory,
Name = destinationFileName,
UploadDate = DateTime.UtcNow,
IsDeleted = false,
Size = fileSize,
};
var entry = db.Files.Add(fileInfo);
await db.SaveChangesAsync(token).ConfigureAwait(false);
return entry.Entity.Id;
}
public async Task<IEnumerable<FileInfoDto>> GetInfosByCategoryAsync(int idWell, int idCategory, CancellationToken token)
{
var entities = await dbSetConfigured
.Where(e => e.IdWell == idWell && e.IdCategory == idCategory && e.IsDeleted == false)
.AsNoTracking()
.ToListAsync(token)
.ConfigureAwait(false);
var dtos = entities.Select(e => Convert(e));
return dtos;
}
public async Task<PaginationContainer<FileInfoDto>> GetInfosAsync(int idWell,
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
.Where(e => e.IdWell == idWell &&
e.IdCategory == idCategory &&
!e.IsDeleted);
if (!string.IsNullOrEmpty(companyName))
query = query.Where(e => (e.Author == null) ||
(e.Author.Company == null) ||
e.Author.Company.Caption.Contains(companyName));
if (!string.IsNullOrEmpty(fileName))
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,
Take = take,
Count = count,
};
if (count <= skip)
return result;
query = query.OrderBy(e => e.UploadDate);
if (skip > 0)
query = query.Skip(skip);
query = query.Take(take);
var entities = await query
.Take(take).AsNoTracking().ToListAsync(token)
.ConfigureAwait(false);
var dtos = entities.Select(e => Convert(e, timezoneOffset));
result.Items.AddRange(dtos);
return result;
}
public async Task<FileInfoDto> GetInfoAsync(int idFile, CancellationToken token)
{
var entity = await dbSetConfigured
.AsNoTracking()
.FirstOrDefaultAsync(f => f.Id == idFile, token)
.ConfigureAwait(false);
if (entity is null)
{
throw new FileNotFoundException($"fileId:{idFile} not found");
}
var dto = Convert(entity);
return dto;
}
public async Task<IEnumerable<FileInfoDto>> GetInfoByIdsAsync(IEnumerable<int> idsFile, CancellationToken token)
{
var result = new List<FileInfoDto>();
var entities = await dbSetConfigured
.AsNoTracking()
.Where(f => idsFile.Contains(f.Id))
.ToListAsync(token)
.ConfigureAwait(false);
foreach (var entity in entities)
{
if (entity is null)
{
throw new FileNotFoundException($"fileId:{entity.Id} not found");
}
result.Add(Convert(entity));
}
return result;
}
public async Task<int> MarkAsDeletedAsync(int idFile, CancellationToken token = default)
{
var fileInfo = await db.Files.FirstOrDefaultAsync(f => f.Id == idFile, token).ConfigureAwait(false);
if (fileInfo is null)
return 0;
fileInfo.IsDeleted = true;
return await db.SaveChangesAsync(token).ConfigureAwait(false);
}
public async Task<IEnumerable<FileInfoDto>> DeleteAsync(IEnumerable<int> ids, CancellationToken token)
{
var filesQuery = db.Files
.Where(f => ids.Contains(f.Id));
var files = await filesQuery.ToListAsync(token);
var filesDtos = files.Select(x => new FileInfoDto {
Id = x.Id,
IdWell = x.Id,
IdCategory = x.IdCategory,
Name = x.Name
});
db.Files.RemoveRange(filesQuery);
await db.SaveChangesAsync(token).ConfigureAwait(false);
return filesDtos;
}
public async Task<FileInfoDto> GetByMarkId(int idMark,
CancellationToken token)
{
var entity = await dbSetConfigured
.FirstOrDefaultAsync(f => f.FileMarks.Any(m => m.Id == idMark), token)
.ConfigureAwait(false);
FileInfoDto dto = Convert(entity);
return dto;
}
public async Task<int> CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token)
{
var fileMark = await db.FileMarks
.FirstOrDefaultAsync(m => m.IdFile == fileMarkDto.IdFile &&
m.IdMarkType == fileMarkDto.IdMarkType &&
m.IdUser == idUser &&
m.IsDeleted == false,
token)
.ConfigureAwait(false);
if (fileMark is not null)
return 0;
var newFileMark = fileMarkDto.Adapt<FileMark>();
newFileMark.Id = default;
newFileMark.DateCreated = DateTime.UtcNow;
newFileMark.IdUser = idUser;
newFileMark.User = null;
db.FileMarks.Add(newFileMark);
return await db.SaveChangesAsync(token);
}
public async Task<int> MarkFileMarkAsDeletedAsync(IEnumerable<int> idsMarks, CancellationToken token)
{
var fileMarkQuery = db.FileMarks
.Where(m => idsMarks.Contains(m.Id));
foreach (var fileMark in fileMarkQuery)
fileMark.IsDeleted = true;
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;
}
}
}

View File

@ -0,0 +1,120 @@
using AsbCloudApp.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Repository
{
/// <summary>
/// Сервис доступа к файлам
/// </summary>
public interface IFileRepository
{
/// <summary>
/// Добавление, в БД, информации о файле
/// </summary>
/// <param name="idWell"></param>
/// <param name="idUser"></param>
/// <param name="idCategory"></param>
/// <param name="destinationFileName"></param>
/// <param name="fileSize"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> AddAsync(int idWell, int? idUser, int idCategory,
string destinationFileName, long fileSize, CancellationToken token = default);
/// <summary>
/// Получить файлы определенной категории
/// </summary>
/// <param name="idWell"></param>
/// <param name="idCategory"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<FileInfoDto>> GetInfosByCategoryAsync(int idWell, int idCategory, CancellationToken token);
/// <summary>
/// Получить список файлов в контейнере
/// </summary>
/// <param name="idWell"></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>
/// <returns></returns>
Task<PaginationContainer<FileInfoDto>> GetInfosAsync(int idWell,
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>
/// <param name="idFile"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<FileInfoDto> GetInfoAsync(int idFile, CancellationToken token);
/// <summary>
/// Пометить файл как удаленный
/// </summary>
/// <param name="idFile"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> MarkAsDeletedAsync(int idFile, CancellationToken token = default);
/// <summary>
/// удалить файлы
/// </summary>
/// <param name="ids"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<FileInfoDto>> DeleteAsync(IEnumerable<int> ids, CancellationToken token);
/// <summary>
/// получить инфо о файле по метке
/// </summary>
/// <param name="idMark"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<FileInfoDto> GetByMarkId(int idMark, CancellationToken token);
/// <summary>
/// добавить метку на файл
/// </summary>
/// <param name="fileMarkDto"></param>
/// <param name="idUser"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token);
/// <summary>
/// Инфо о файлах
/// </summary>
/// <param name="idsFile"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<FileInfoDto>> GetInfoByIdsAsync(IEnumerable<int> idsFile, CancellationToken token);
/// <summary>
/// пометить метки файлов как удаленные
/// </summary>
/// <param name="idsMarks"></param>
/// <param name="token"></param>
/// <returns></returns>
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);
}
}

View File

@ -2,6 +2,7 @@
using AsbCloudApp.Exceptions; using AsbCloudApp.Exceptions;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@ -22,6 +23,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
private readonly IFileService fileService; private readonly IFileService fileService;
private readonly IUserService userService; private readonly IUserService userService;
private readonly IWellService wellService; private readonly IWellService wellService;
private readonly IFileRepository fileRepository;
private readonly IConfiguration configuration; private readonly IConfiguration configuration;
private readonly IBackgroundWorkerService backgroundWorker; private readonly IBackgroundWorkerService backgroundWorker;
private readonly IEmailService emailService; private readonly IEmailService emailService;
@ -52,6 +54,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
IFileService fileService, IFileService fileService,
IUserService userService, IUserService userService,
IWellService wellService, IWellService wellService,
IFileRepository fileRepository,
IConfiguration configuration, IConfiguration configuration,
IBackgroundWorkerService backgroundWorker, IBackgroundWorkerService backgroundWorker,
IEmailService emailService) IEmailService emailService)
@ -60,6 +63,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
this.fileService = fileService; this.fileService = fileService;
this.userService = userService; this.userService = userService;
this.wellService = wellService; this.wellService = wellService;
this.fileRepository = fileRepository;
this.configuration = configuration; this.configuration = configuration;
this.backgroundWorker = backgroundWorker; this.backgroundWorker = backgroundWorker;
this.connectionString = configuration.GetConnectionString("DefaultConnection"); this.connectionString = configuration.GetConnectionString("DefaultConnection");
@ -308,9 +312,9 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
.Select(m => m.Id); .Select(m => m.Id);
if (oldMarksIds?.Any() == true) if (oldMarksIds?.Any() == true)
await fileService.MarkFileMarkAsDeletedAsync(oldMarksIds, token); await fileRepository.MarkFileMarkAsDeletedAsync(oldMarksIds, token);
var result = await fileService.CreateFileMarkAsync(fileMarkDto, idUser, token) var result = await fileRepository.CreateFileMarkAsync(fileMarkDto, idUser, token)
.ConfigureAwait(false); .ConfigureAwait(false);
if (fileMarkDto.IdMarkType == idMarkTypeReject) if (fileMarkDto.IdMarkType == idMarkTypeReject)
@ -340,7 +344,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
public async Task<int> MarkAsDeletedFileMarkAsync(int idMark, public async Task<int> MarkAsDeletedFileMarkAsync(int idMark,
CancellationToken token) CancellationToken token)
{ {
var fileInfo = await fileService.GetByMarkId(idMark, token) var fileInfo = await fileRepository.GetByMarkId(idMark, token)
.ConfigureAwait(false); .ConfigureAwait(false);
if (fileInfo.IdCategory < idFileCategoryDrillingProgramPartsStart || if (fileInfo.IdCategory < idFileCategoryDrillingProgramPartsStart ||
@ -479,7 +483,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
.UseNpgsql(connectionString) .UseNpgsql(connectionString)
.Options; .Options;
using var context = new AsbCloudDbContext(contextOptions); using var context = new AsbCloudDbContext(contextOptions);
var fileService = new FileService(context); var fileService = new FileService(fileRepository);
var files = state.Parts.Select(p => fileService.GetUrl(p.File)); var files = state.Parts.Select(p => fileService.GetUrl(p.File));
DrillingProgramMaker.UniteExcelFiles(files, tempResultFilePath, state.Parts, well); DrillingProgramMaker.UniteExcelFiles(files, tempResultFilePath, state.Parts, well);
await fileService.MoveAsync(idWell, null, idFileCategoryDrillingProgram, resultFileName, tempResultFilePath, token); await fileService.MoveAsync(idWell, null, idFileCategoryDrillingProgram, resultFileName, tempResultFilePath, token);

View File

@ -2,6 +2,7 @@
using AsbCloudApp.Exceptions; using AsbCloudApp.Exceptions;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
@ -16,21 +17,12 @@ namespace AsbCloudInfrastructure.Services
public class FileService : IFileService public class FileService : IFileService
{ {
public string RootPath { get; private set; } public string RootPath { get; private set; }
private readonly IFileRepository fileRepository;
private readonly IQueryable<AsbCloudDb.Model.FileInfo> dbSetConfigured; public FileService(IFileRepository fileRepository)
private readonly IAsbCloudDbContext db;
public FileService(IAsbCloudDbContext db)
{ {
RootPath = "files"; RootPath = "files";
this.db = db; this.fileRepository = fileRepository;
dbSetConfigured = db.Files
.Include(f => f.Author)
.ThenInclude(u => u.Company)
.ThenInclude(c => c.CompanyType)
.Include(f => f.FileMarks)
.ThenInclude(m => m.User)
.Include(f => f.Well);
} }
public async Task<FileInfoDto> MoveAsync(int idWell, int? idUser, int idCategory, public async Task<FileInfoDto> MoveAsync(int idWell, int? idUser, int idCategory,
@ -44,45 +36,23 @@ namespace AsbCloudInfrastructure.Services
var sysFileInfo = new System.IO.FileInfo(srcFilePath); var sysFileInfo = new System.IO.FileInfo(srcFilePath);
//save info to db //save info to db
var fileInfo = new AsbCloudDb.Model.FileInfo() var fileId = await fileRepository.AddAsync(idWell, idUser, idCategory, destinationFileName, sysFileInfo.Length, token)
{ .ConfigureAwait(false);
IdWell = idWell,
IdAuthor = idUser,
IdCategory = idCategory,
Name = destinationFileName,
UploadDate = DateTime.UtcNow,
IsDeleted = false,
Size = sysFileInfo.Length,
};
var entry = db.Files.Add(fileInfo);
await db.SaveChangesAsync(token).ConfigureAwait(false);
var fileId = entry.Entity.Id;
string filePath = MakeFilePath(idWell, idCategory, destinationFileName, fileId); string filePath = MakeFilePath(idWell, idCategory, destinationFileName, fileId);
Directory.CreateDirectory(Path.GetDirectoryName(filePath)); Directory.CreateDirectory(Path.GetDirectoryName(filePath));
File.Move(srcFilePath, filePath); File.Move(srcFilePath, filePath);
return await GetInfoAsync(entry.Entity.Id, token); return await GetInfoAsync(fileId, token);
} }
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
var fileInfo = new AsbCloudDb.Model.FileInfo() var fileId = await fileRepository.AddAsync(idWell, idUser, idCategory, Path.GetFileName(fileFullName), fileStream?.Length ?? 0, token)
{ .ConfigureAwait(false);
IdWell = idWell,
IdAuthor = idUser,
IdCategory = idCategory,
Name = Path.GetFileName(fileFullName),
UploadDate = DateTime.UtcNow,
IsDeleted = false,
Size = fileStream?.Length ?? 0
};
var entry = db.Files.Add(fileInfo);
await db.SaveChangesAsync(token).ConfigureAwait(false);
var fileId = entry.Entity.Id;
//save stream to disk //save stream to disk
string filePath = MakeFilePath(idWell, idCategory, fileFullName, fileId); string filePath = MakeFilePath(idWell, idCategory, fileFullName, fileId);
@ -91,7 +61,7 @@ namespace AsbCloudInfrastructure.Services
using var newfileStream = new FileStream(filePath, FileMode.Create); using var newfileStream = new FileStream(filePath, FileMode.Create);
await fileStream.CopyToAsync(newfileStream, token).ConfigureAwait(false); await fileStream.CopyToAsync(newfileStream, token).ConfigureAwait(false);
return await GetInfoAsync(entry.Entity.Id, token); return await GetInfoAsync(fileId, token);
} }
private string MakeFilePath(int idWell, int idCategory, string fileFullName, int fileId) private string MakeFilePath(int idWell, int idCategory, string fileFullName, int fileId)
@ -100,125 +70,23 @@ namespace AsbCloudInfrastructure.Services
$"{idCategory}", $"{fileId}" + $"{Path.GetExtension(fileFullName)}"); $"{idCategory}", $"{fileId}" + $"{Path.GetExtension(fileFullName)}");
} }
public async Task<IEnumerable<FileInfoDto>> GetInfosByCategoryAsync(int idWell,
int idCategory, CancellationToken token)
{
var entities = await dbSetConfigured
.Where(e => e.IdWell == idWell && e.IdCategory == idCategory && e.IsDeleted == false)
.AsNoTracking()
.ToListAsync(token)
.ConfigureAwait(false);
var dtos = entities.Select(e => Convert(e));
return dtos;
}
public async Task<PaginationContainer<FileInfoDto>> GetInfosAsync(int idWell,
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
.Where(e => e.IdWell == idWell &&
e.IdCategory == idCategory &&
!e.IsDeleted);
if (!string.IsNullOrEmpty(companyName))
query = query.Where(e => (e.Author == null) ||
(e.Author.Company == null) ||
e.Author.Company.Caption.Contains(companyName));
if (!string.IsNullOrEmpty(fileName))
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,
Take = take,
Count = count,
};
if (count <= skip)
return result;
query = query.OrderBy(e => e.UploadDate);
if (skip > 0)
query = query.Skip(skip);
query = query.Take(take);
var entities = await query
.Take(take).AsNoTracking().ToListAsync(token)
.ConfigureAwait(false);
var dtos = entities.Select(e => Convert(e, timezoneOffset));
result.Items.AddRange(dtos);
return result;
}
public async Task<FileInfoDto> GetInfoAsync(int idFile, public async Task<FileInfoDto> GetInfoAsync(int idFile,
CancellationToken token) CancellationToken token)
{ {
var entity = await dbSetConfigured var dto = await fileRepository.GetInfoAsync(idFile, token).ConfigureAwait(false);
.AsNoTracking()
.FirstOrDefaultAsync(f => f.Id == idFile, token)
.ConfigureAwait(false);
if (entity is null) var ext = Path.GetExtension(dto.Name);
{
throw new FileNotFoundException($"fileId:{idFile} not found");
}
var ext = Path.GetExtension(entity.Name); var relativePath = GetUrl(dto.IdWell, dto.IdCategory, dto.Id, ext);
var relativePath = GetUrl(entity.IdWell, entity.IdCategory, entity.Id, ext);
var fullPath = Path.GetFullPath(relativePath); var fullPath = Path.GetFullPath(relativePath);
if (!File.Exists(fullPath)) if (!File.Exists(fullPath))
{ {
throw new FileNotFoundException("not found", relativePath); throw new FileNotFoundException("not found", relativePath);
} }
var dto = Convert(entity);
return dto; return dto;
} }
public async Task<int> MarkAsDeletedAsync(int idFile,
CancellationToken token = default)
{
var fileInfo = await db.Files.FirstOrDefaultAsync(f => f.Id == idFile, token).ConfigureAwait(false);
if (fileInfo is null)
return 0;
fileInfo.IsDeleted = true;
return await db.SaveChangesAsync(token).ConfigureAwait(false);
}
public Task<int> DeleteAsync(int idFile, CancellationToken token) public Task<int> DeleteAsync(int idFile, CancellationToken token)
=> DeleteAsync(new int[] { idFile }, token); => DeleteAsync(new int[] { idFile }, token);
@ -227,10 +95,7 @@ namespace AsbCloudInfrastructure.Services
if (ids is null || !ids.Any()) if (ids is null || !ids.Any())
return 0; return 0;
var filesQuery = db.Files var files = await fileRepository.DeleteAsync(ids, token).ConfigureAwait(false);
.Where(f => ids.Contains(f.Id));
var files = await filesQuery.ToListAsync(token);
if (files is null || !files.Any()) if (files is null || !files.Any())
return 0; return 0;
@ -242,18 +107,12 @@ namespace AsbCloudInfrastructure.Services
File.Delete(fileName); File.Delete(fileName);
} }
db.Files.RemoveRange(filesQuery); return files.Any() ? 1 : 0;
return await db.SaveChangesAsync(token).ConfigureAwait(false);
} }
public string GetUrl(int idFile) public async Task<string> GetUrl(int idFile)
{ {
var fileInfo = db.Files var fileInfo = await fileRepository.GetInfoAsync(idFile, CancellationToken.None).ConfigureAwait(false);
.FirstOrDefault(f => f.Id == idFile);
if (fileInfo is null)
return null;
return GetUrl(fileInfo.IdWell, fileInfo.IdCategory, fileInfo.Id, Path.GetExtension(fileInfo.Name)); return GetUrl(fileInfo.IdWell, fileInfo.IdCategory, fileInfo.Id, Path.GetExtension(fileInfo.Name));
} }
@ -264,116 +123,27 @@ namespace AsbCloudInfrastructure.Services
public string GetUrl(int idWell, int idCategory, int idFile, string dotExtention) => public string GetUrl(int idWell, int idCategory, int idFile, string dotExtention) =>
Path.Combine(RootPath, idWell.ToString(), idCategory.ToString(), $"{idFile}{dotExtention}"); Path.Combine(RootPath, idWell.ToString(), idCategory.ToString(), $"{idFile}{dotExtention}");
public async Task<FileInfoDto> GetByMarkId(int idMark,
CancellationToken token)
{
var entity = await dbSetConfigured
.FirstOrDefaultAsync(f => f.FileMarks.Any(m => m.Id == idMark), token)
.ConfigureAwait(false);
FileInfoDto dto = Convert(entity);
return dto;
}
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<int> CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token)
{
var fileMark = await db.FileMarks
.FirstOrDefaultAsync(m => m.IdFile == fileMarkDto.IdFile &&
m.IdMarkType == fileMarkDto.IdMarkType &&
m.IdUser == idUser &&
m.IsDeleted == false,
token)
.ConfigureAwait(false);
if (fileMark is not null)
return 0;
var newFileMark = fileMarkDto.Adapt<FileMark>();
newFileMark.Id = default;
newFileMark.DateCreated = DateTime.UtcNow;
newFileMark.IdUser = idUser;
newFileMark.User = null;
db.FileMarks.Add(newFileMark);
return await db.SaveChangesAsync(token);
}
public Task<int> MarkFileMarkAsDeletedAsync(int idMark, public Task<int> MarkFileMarkAsDeletedAsync(int idMark,
CancellationToken token) CancellationToken token)
=> MarkFileMarkAsDeletedAsync(new int[] { idMark }, token); => fileRepository.MarkFileMarkAsDeletedAsync(new int[] { idMark }, token);
public async Task<int> MarkFileMarkAsDeletedAsync(IEnumerable<int> idsMarks, public async Task<IEnumerable<FileInfoDto>> GetInfoByIdsAsync(IEnumerable<int> idsFile, CancellationToken token)
CancellationToken token)
{ {
var fileMarkQuery = db.FileMarks var result = await fileRepository.GetInfoByIdsAsync(idsFile, token).ConfigureAwait(false);
.Where(m => idsMarks.Contains(m.Id));
foreach (var fileMark in fileMarkQuery) foreach (var entity in result)
fileMark.IsDeleted = true;
return await db.SaveChangesAsync(token);
}
public async Task<List<FileInfoDto>> GetInfoByIdsAsync(List<int> idsFile, CancellationToken token)
{
var result = new List<FileInfoDto>();
var entities = await dbSetConfigured
.AsNoTracking()
.Where(f => idsFile.Contains(f.Id))
.ToListAsync(token)
.ConfigureAwait(false);
foreach (var entity in entities)
{ {
if (entity is null)
{
throw new FileNotFoundException($"fileId:{entity.Id} not found");
}
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);
if (!File.Exists(fullPath)) if (!File.Exists(fullPath))
{ {
throw new FileNotFoundException("not found", relativePath); throw new FileNotFoundException("not found", relativePath);
} }
result.Add(Convert(entity));
} }
return result; return result;
} }
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;
}
} }
} }

View File

@ -1,6 +1,7 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository;
using AsbSaubReport; using AsbSaubReport;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@ -21,15 +22,17 @@ namespace AsbCloudInfrastructure.Services
private readonly ITelemetryService telemetryService; private readonly ITelemetryService telemetryService;
private readonly IWellService wellService; private readonly IWellService wellService;
private readonly IBackgroundWorkerService backgroundWorkerService; private readonly IBackgroundWorkerService backgroundWorkerService;
private readonly IFileRepository fileRepository;
public ReportService(IAsbCloudDbContext db, IConfiguration configuration, public ReportService(IAsbCloudDbContext db, IConfiguration configuration,
ITelemetryService telemetryService, IWellService wellService, IBackgroundWorkerService backgroundWorkerService) ITelemetryService telemetryService, IWellService wellService, IBackgroundWorkerService backgroundWorkerService, IFileRepository fileRepository)
{ {
this.db = db; this.db = db;
this.connectionString = configuration.GetConnectionString("DefaultConnection"); this.connectionString = configuration.GetConnectionString("DefaultConnection");
this.wellService = wellService; this.wellService = wellService;
this.backgroundWorkerService = backgroundWorkerService; this.backgroundWorkerService = backgroundWorkerService;
this.telemetryService = telemetryService; this.telemetryService = telemetryService;
this.fileRepository = fileRepository;
ReportCategoryId = db.FileCategories.AsNoTracking() ReportCategoryId = db.FileCategories.AsNoTracking()
.FirstOrDefault(c => .FirstOrDefault(c =>
c.Name.Equals("Рапорт")).Id; c.Name.Equals("Рапорт")).Id;
@ -65,7 +68,7 @@ namespace AsbCloudInfrastructure.Services
}; };
generator.Make(reportFileName); generator.Make(reportFileName);
var fileService = new FileService(context); var fileService = new FileService(fileRepository);
var fileInfo = await fileService.MoveAsync(idWell, idUser, ReportCategoryId, reportFileName, reportFileName, token); var fileInfo = await fileService.MoveAsync(idWell, idUser, ReportCategoryId, reportFileName, reportFileName, token);
progressHandler.Invoke(new progressHandler.Invoke(new

View File

@ -2,6 +2,7 @@
using AsbCloudApp.Exceptions; using AsbCloudApp.Exceptions;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@ -27,6 +28,7 @@ namespace AsbCloudInfrastructure.Services
private readonly IConfiguration configuration; private readonly IConfiguration configuration;
private readonly IEmailService emailService; private readonly IEmailService emailService;
private readonly IFileCategoryService fileCategoryService; private readonly IFileCategoryService fileCategoryService;
private readonly IFileRepository fileRepository;
private const int FileServiceThrewException = -1; private const int FileServiceThrewException = -1;
@ -36,7 +38,8 @@ namespace AsbCloudInfrastructure.Services
IWellService wellService, IWellService wellService,
IConfiguration configuration, IConfiguration configuration,
IEmailService emailService, IEmailService emailService,
IFileCategoryService fileCategoryService) IFileCategoryService fileCategoryService,
IFileRepository fileRepository)
{ {
this.context = context; this.context = context;
this.fileService = fileService; this.fileService = fileService;
@ -45,6 +48,7 @@ namespace AsbCloudInfrastructure.Services
this.configuration = configuration; this.configuration = configuration;
this.emailService = emailService; this.emailService = emailService;
this.fileCategoryService = fileCategoryService; this.fileCategoryService = fileCategoryService;
this.fileRepository = fileRepository;
} }
public async Task<int> UpdateRangeAsync(int idWell, IEnumerable<WellFinalDocumentInputDto>? dtos, CancellationToken token) public async Task<int> UpdateRangeAsync(int idWell, IEnumerable<WellFinalDocumentInputDto>? dtos, CancellationToken token)
@ -94,7 +98,7 @@ namespace AsbCloudInfrastructure.Services
var categoriesIds = entitiesGroups var categoriesIds = entitiesGroups
.Select(g => g.Key); .Select(g => g.Key);
var files = (await fileService var files = (await fileRepository
.GetInfosByWellIdAsync(idWell, token) .GetInfosByWellIdAsync(idWell, token)
.ConfigureAwait(false)) .ConfigureAwait(false))
.Where(f => categoriesIds.Contains(f.IdCategory)) .Where(f => categoriesIds.Contains(f.IdCategory))
@ -161,7 +165,7 @@ 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 files = await fileRepository.GetInfosByCategoryAsync(idWell, idCategory, token).ConfigureAwait(false);
return new WellFinalDocumentsHistoryDto { return new WellFinalDocumentsHistoryDto {
IdWell = idWell, IdWell = idWell,

View File

@ -1,5 +1,6 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudInfrastructure.Repository;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@ -20,11 +21,13 @@ namespace AsbCloudWebApi.Controllers
{ {
private readonly IFileService fileService; private readonly IFileService fileService;
private readonly IWellService wellService; private readonly IWellService wellService;
private readonly IFileRepository fileRepository;
public FileController(IFileService fileService, IWellService wellService) public FileController(IFileService fileService, IWellService wellService, IFileRepository fileRepository)
{ {
this.fileService = fileService; this.fileService = fileService;
this.wellService = wellService; this.wellService = wellService;
this.fileRepository = fileRepository;
} }
/// <summary> /// <summary>
@ -98,7 +101,7 @@ namespace AsbCloudWebApi.Controllers
idWell, token).ConfigureAwait(false)) idWell, token).ConfigureAwait(false))
return Forbid(); return Forbid();
var filesInfo = await fileService.GetInfosAsync(idWell, idCategory, var filesInfo = await fileRepository.GetInfosAsync(idWell, idCategory,
companyName, fileName, begin, end, skip, take, token).ConfigureAwait(false); companyName, fileName, begin, end, skip, take, token).ConfigureAwait(false);
return Ok(filesInfo); return Ok(filesInfo);
@ -168,7 +171,7 @@ namespace AsbCloudWebApi.Controllers
if (!userService.HasPermission((int)idUser, $"File.edit{file.IdCategory}")) if (!userService.HasPermission((int)idUser, $"File.edit{file.IdCategory}"))
return Forbid(); return Forbid();
var result = await fileService.MarkAsDeletedAsync(idFile, token); var result = await fileRepository.MarkAsDeletedAsync(idFile, token);
return Ok(result); return Ok(result);
} }
@ -193,7 +196,7 @@ namespace AsbCloudWebApi.Controllers
idWell, token).ConfigureAwait(false)) idWell, token).ConfigureAwait(false))
return Forbid(); return Forbid();
var result = await fileService.CreateFileMarkAsync(markDto, (int)idUser, token) var result = await fileRepository.CreateFileMarkAsync(markDto, (int)idUser, token)
.ConfigureAwait(false); .ConfigureAwait(false);
return Ok(result); return Ok(result);
@ -223,5 +226,33 @@ namespace AsbCloudWebApi.Controllers
return Ok(result); return Ok(result);
} }
/// <summary>
/// Возвращает информацию о файле
/// </summary>
/// <param name="idFile">id запрашиваемого файла</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>Запрашиваемый файл</returns>
[HttpGet]
[Route("/api/files/{idFile}")]
[Permission]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetFileInfoByIdAsync([FromRoute] int idFile, CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
if (idCompany is null)
return Forbid();
try
{
var fileInfo = await fileRepository.GetInfoAsync(idFile, token).ConfigureAwait(false);
return Ok(fileInfo);
}
catch (FileNotFoundException ex)
{
return NotFound(ex.FileName);
}
}
} }
} }