Merge branch 'feature/file_repository' into dev

This commit is contained in:
ngfrolov 2022-10-04 09:43:22 +05:00
commit c891c78782
10 changed files with 561 additions and 295 deletions

View File

@ -0,0 +1,97 @@
using AsbCloudApp.Data;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services
{
/// <summary>
/// Сервис доступа к файлам
/// </summary>
public interface IFileRepository : ICrudService<FileInfoDto>
{
/// <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<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

@ -31,23 +31,6 @@ namespace AsbCloudApp.Services
/// <returns></returns>
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>
@ -57,24 +40,6 @@ namespace AsbCloudApp.Services
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="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>
@ -103,7 +68,7 @@ namespace AsbCloudApp.Services
/// </summary>
/// <param name="idFile"></param>
/// <returns></returns>
string GetUrl(int idFile);
Task<string> GetUrl(int idFile);
/// <summary>
/// получить путь для скачивания
@ -115,15 +80,6 @@ namespace AsbCloudApp.Services
/// <returns></returns>
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>
@ -143,7 +99,57 @@ namespace AsbCloudApp.Services
/// <param name="token"></param>
/// <returns></returns>
Task<FileInfoDto> MoveAsync(int idWell, int? idUser, int idCategory, string destinationFileName, string srcFileFullName, CancellationToken token = default);
/// <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="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<int> MarkAsDeletedAsync(int idFile, CancellationToken token = default);
/// <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>
/// Получить запись по id
/// </summary>
/// <param name="id"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<FileInfoDto> GetOrDefaultAsync(int id, CancellationToken token);
/// <summary>
/// получить инфо о файле по метке
/// </summary>
@ -160,14 +166,6 @@ namespace AsbCloudApp.Services
/// <returns></returns>
Task<int> MarkFileMarkAsDeletedAsync(IEnumerable<int> idsMarks, CancellationToken token);
/// <summary>
/// Инфо о файле
/// </summary>
/// <param name="idsFile"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<List<FileInfoDto>> GetInfoByIdsAsync(List<int> idsFile, CancellationToken token);
/// <summary>
/// Получение файлов по скважине
/// </summary>
@ -175,5 +173,14 @@ namespace AsbCloudApp.Services
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<FileInfoDto>> GetInfosByWellIdAsync(int idWell, CancellationToken token);
/// <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);
}
}

View File

@ -158,6 +158,7 @@ namespace AsbCloudInfrastructure
dbSet => dbSet
.Include(c => c.Wells)
.Include(c => c.Deposit))); // может быть включен в сервис ClusterService
services.AddTransient<IFileRepository, FileRepository>();
// Subsystem service
services.AddTransient<ICrudService<SubsystemDto>, CrudCacheServiceBase<SubsystemDto, Subsystem>>();
services.AddTransient<ISubsystemService, SubsystemService>();

View File

@ -0,0 +1,305 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
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<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<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 query = dbSetConfigured
.Where(f => ids.Contains(f.Id) && f.IsDeleted);
var files = await query.ToListAsync(token);
var filesDtos = files.Select(x => Convert(x));
db.Files.RemoveRange(query);
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;
}
public async Task<IEnumerable<FileInfoDto>> GetAllAsync(CancellationToken token)
=> await dbSetConfigured.AsNoTracking()
.Select(x => Convert(x))
.ToListAsync(token)
.ConfigureAwait(false);
public async Task<FileInfoDto> GetOrDefaultAsync(int id, CancellationToken token)
{
var entity = await dbSetConfigured
.AsNoTracking()
.FirstOrDefaultAsync(f => f.Id == id, token)
.ConfigureAwait(false);
if (entity is null)
{
throw new FileNotFoundException($"fileId:{id} not found");
}
var dto = Convert(entity);
return dto;
}
public FileInfoDto GetOrDefault(int id)
{
var entity = dbSetConfigured
.AsNoTracking()
.FirstOrDefault(f => f.Id == id);
if (entity is null)
{
throw new FileNotFoundException($"fileId:{id} not found");
}
var dto = Convert(entity);
return dto;
}
public async Task<int> InsertAsync(FileInfoDto newItem, CancellationToken token)
{
var fileInfo = new AsbCloudDb.Model.FileInfo()
{
IdWell = newItem.IdWell,
IdAuthor = newItem.IdAuthor,
IdCategory = newItem.IdCategory,
Name = newItem.Name,
UploadDate = DateTime.UtcNow,
IsDeleted = false,
Size = newItem.Size,
};
var entry = db.Files.Add(fileInfo);
await db.SaveChangesAsync(token).ConfigureAwait(false);
return entry.Entity.Id;
}
public Task<int> InsertRangeAsync(IEnumerable<FileInfoDto> newItems, CancellationToken token)
{
throw new NotImplementedException();
}
public Task<int> UpdateAsync(FileInfoDto item, CancellationToken token)
{
throw new NotImplementedException();
}
public Task<int> DeleteAsync(int id, CancellationToken token)
{
throw new NotImplementedException();
}
}
}

View File

@ -2,6 +2,7 @@
using AsbCloudApp.Exceptions;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository;
using Mapster;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
@ -479,7 +480,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
.UseNpgsql(connectionString)
.Options;
using var context = new AsbCloudDbContext(contextOptions);
var fileService = new FileService(context);
var fileRepository = new FileRepository(context);
var fileService = new FileService(fileRepository);
var files = state.Parts.Select(p => fileService.GetUrl(p.File));
DrillingProgramMaker.UniteExcelFiles(files, tempResultFilePath, state.Parts, well);
await fileService.MoveAsync(idWell, null, idFileCategoryDrillingProgram, resultFileName, tempResultFilePath, token);

View File

@ -2,6 +2,7 @@
using AsbCloudApp.Exceptions;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
@ -16,21 +17,12 @@ namespace AsbCloudInfrastructure.Services
public class FileService : IFileService
{
public string RootPath { get; private set; }
private readonly IFileRepository fileRepository;
private readonly IQueryable<AsbCloudDb.Model.FileInfo> dbSetConfigured;
private readonly IAsbCloudDbContext db;
public FileService(IAsbCloudDbContext db)
public FileService(IFileRepository fileRepository)
{
RootPath = "files";
this.db = db;
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);
this.fileRepository = fileRepository;
}
public async Task<FileInfoDto> MoveAsync(int idWell, int? idUser, int idCategory,
@ -44,45 +36,39 @@ namespace AsbCloudInfrastructure.Services
var sysFileInfo = new System.IO.FileInfo(srcFilePath);
//save info to db
var fileInfo = new AsbCloudDb.Model.FileInfo()
{
var dto = new FileInfoDto {
IdWell = idWell,
IdAuthor = idUser,
IdCategory = idCategory,
Name = destinationFileName,
UploadDate = DateTime.UtcNow,
IsDeleted = false,
Size = sysFileInfo.Length,
Size = sysFileInfo.Length
};
var entry = db.Files.Add(fileInfo);
await db.SaveChangesAsync(token).ConfigureAwait(false);
var fileId = entry.Entity.Id;
var fileId = await fileRepository.InsertAsync(dto, token)
.ConfigureAwait(false);
string filePath = MakeFilePath(idWell, idCategory, destinationFileName, fileId);
Directory.CreateDirectory(Path.GetDirectoryName(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,
string fileFullName, Stream fileStream, CancellationToken token)
{
//save info to db
var fileInfo = new AsbCloudDb.Model.FileInfo()
var dto = new FileInfoDto
{
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;
var fileId = await fileRepository.InsertAsync(dto, token)
.ConfigureAwait(false);
//save stream to disk
string filePath = MakeFilePath(idWell, idCategory, fileFullName, fileId);
@ -91,7 +77,7 @@ namespace AsbCloudInfrastructure.Services
using var newfileStream = new FileStream(filePath, FileMode.Create);
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)
@ -100,137 +86,32 @@ namespace AsbCloudInfrastructure.Services
$"{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,
CancellationToken token)
{
var entity = await dbSetConfigured
.AsNoTracking()
.FirstOrDefaultAsync(f => f.Id == idFile, token)
.ConfigureAwait(false);
var dto = await fileRepository.GetOrDefaultAsync(idFile, token).ConfigureAwait(false);
if (entity is null)
{
throw new FileNotFoundException($"fileId:{idFile} not found");
}
var ext = Path.GetExtension(dto.Name);
var ext = Path.GetExtension(entity.Name);
var relativePath = GetUrl(entity.IdWell, entity.IdCategory, entity.Id, ext);
var relativePath = GetUrl(dto.IdWell, dto.IdCategory, dto.Id, ext);
var fullPath = Path.GetFullPath(relativePath);
if (!File.Exists(fullPath))
{
throw new FileNotFoundException("not found", relativePath);
}
var dto = Convert(entity);
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)
=> DeleteAsync(new int[] { idFile }, token);
=> DeleteAsync(new int[] { idFile }, token);
public async Task<int> DeleteAsync(IEnumerable<int> ids, CancellationToken token)
{
if (ids is null || !ids.Any())
return 0;
var filesQuery = db.Files
.Where(f => ids.Contains(f.Id));
var files = await filesQuery.ToListAsync(token);
var files = await fileRepository.DeleteAsync(ids, token).ConfigureAwait(false);
if (files is null || !files.Any())
return 0;
@ -242,18 +123,12 @@ namespace AsbCloudInfrastructure.Services
File.Delete(fileName);
}
db.Files.RemoveRange(filesQuery);
return await db.SaveChangesAsync(token).ConfigureAwait(false);
return files.Any() ? 1 : 0;
}
public string GetUrl(int idFile)
public async Task<string> GetUrl(int idFile)
{
var fileInfo = db.Files
.FirstOrDefault(f => f.Id == idFile);
if (fileInfo is null)
return null;
var fileInfo = await fileRepository.GetOrDefaultAsync(idFile, CancellationToken.None).ConfigureAwait(false);
return GetUrl(fileInfo.IdWell, fileInfo.IdCategory, fileInfo.Id, Path.GetExtension(fileInfo.Name));
}
@ -264,116 +139,61 @@ namespace AsbCloudInfrastructure.Services
public string GetUrl(int idWell, int idCategory, int idFile, string 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,
CancellationToken token)
=> MarkFileMarkAsDeletedAsync(new int[] { idMark }, token);
=> fileRepository.MarkFileMarkAsDeletedAsync(new int[] { idMark }, token);
public async Task<int> MarkFileMarkAsDeletedAsync(IEnumerable<int> idsMarks,
CancellationToken token)
public async Task<IEnumerable<FileInfoDto>> GetInfoByIdsAsync(IEnumerable<int> idsFile, CancellationToken token)
{
var fileMarkQuery = db.FileMarks
.Where(m => idsMarks.Contains(m.Id));
var result = await fileRepository.GetInfoByIdsAsync(idsFile, token).ConfigureAwait(false);
foreach (var fileMark in fileMarkQuery)
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)
foreach (var entity in result)
{
if (entity is null)
{
throw new FileNotFoundException($"fileId:{entity.Id} not found");
}
var ext = Path.GetExtension(entity.Name);
var relativePath = GetUrl(entity.IdWell, entity.IdCategory, entity.Id, ext);
var fullPath = Path.GetFullPath(relativePath);
if (!File.Exists(fullPath))
{
throw new FileNotFoundException("not found", relativePath);
}
result.Add(Convert(entity));
}
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)
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)
=> await fileRepository.GetInfosAsync(idWell, idCategory, companyName, fileName, begin, end, skip, take, token)
.ConfigureAwait(false);
var dtos = entities.Select(e => Convert(e));
return dtos;
}
public async Task<int> MarkAsDeletedAsync(int idFile, CancellationToken token = default)
=> await fileRepository.MarkAsDeletedAsync(idFile, token)
.ConfigureAwait(false);
public async Task<int> CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token)
=> await fileRepository.CreateFileMarkAsync(fileMarkDto, idUser, token)
.ConfigureAwait(false);
public async Task<FileInfoDto> GetOrDefaultAsync(int id, CancellationToken token)
=> await fileRepository.GetOrDefaultAsync(id, token)
.ConfigureAwait(false);
public async Task<FileInfoDto> GetByMarkId(int idMark, CancellationToken token)
=> await fileRepository.GetByMarkId(idMark, token)
.ConfigureAwait(false);
public async Task<int> MarkFileMarkAsDeletedAsync(IEnumerable<int> idsMarks, CancellationToken token)
=> await fileRepository.MarkFileMarkAsDeletedAsync(idsMarks, token)
.ConfigureAwait(false);
public async Task<IEnumerable<FileInfoDto>> GetInfosByWellIdAsync(int idWell, CancellationToken token)
=> await fileRepository.GetInfosByWellIdAsync(idWell, token)
.ConfigureAwait(false);
public async Task<IEnumerable<FileInfoDto>> GetInfosByCategoryAsync(int idWell, int idCategory, CancellationToken token)
=> await fileRepository.GetInfosByCategoryAsync(idWell, idCategory, token)
.ConfigureAwait(false);
}
}

View File

@ -1,6 +1,7 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository;
using AsbSaubReport;
using Mapster;
using Microsoft.EntityFrameworkCore;
@ -65,7 +66,8 @@ namespace AsbCloudInfrastructure.Services
};
generator.Make(reportFileName);
var fileService = new FileService(context);
var fileRepository = new FileRepository(context);
var fileService = new FileService(fileRepository);
var fileInfo = await fileService.MoveAsync(idWell, idUser, ReportCategoryId, reportFileName, reportFileName, token);
progressHandler.Invoke(new

View File

@ -2,6 +2,7 @@
using AsbCloudApp.Exceptions;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository;
using Mapster;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

View File

@ -1,6 +1,7 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository;
using AsbCloudInfrastructure.Services.DrillingProgram;
using Mapster;
using Microsoft.Extensions.Configuration;

View File

@ -4,6 +4,8 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
@ -223,5 +225,33 @@ namespace AsbCloudWebApi.Controllers
return Ok(result);
}
/// <summary>
/// Возвращает информацию о файле
/// </summary>
/// <param name="idFile">id запрашиваемого файла</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>Запрашиваемый файл</returns>
[HttpGet]
[Route("/api/files/{idFile}")]
[Permission]
[ProducesResponseType(typeof(FileInfoDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetFileInfoAsync([FromRoute] int idFile, CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
if (idCompany is null)
return Forbid();
try
{
var fileInfo = await fileService.GetOrDefaultAsync(idFile, token).ConfigureAwait(false);
return Ok(fileInfo);
}
catch (FileNotFoundException ex)
{
return NotFound(ex.FileName);
}
}
}
}