DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/FileService.cs

115 lines
3.5 KiB
C#

using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services
{
public class FileService : IFileService
{
public string RootPath { get; private set; }
private readonly IAsbCloudDbContext db;
public FileService(IAsbCloudDbContext db)
{
RootPath = "files";
this.db = db;
}
public IDictionary<string, int> SaveFilesPropertiesToDb(int idWell, int idCategory,
IEnumerable<(string fileName, int idWell, int idCategory, DateTime date, int idUser)> filesInfo)
{
var fileIdsToNames = new Dictionary<string, int>();
foreach (var fileInfo in filesInfo)
{
var file = new FileInfo()
{
Name = fileInfo.fileName,
IdWell = fileInfo.idWell,
IdCategory = fileInfo.idCategory,
UploadDate = fileInfo.date,
IdAuthor = fileInfo.idUser
};
db.Files.Add(file);
db.SaveChanges();
fileIdsToNames.Add(file.Name, file.Id);
}
return fileIdsToNames;
}
public async Task<PaginationContainer<FileInfoDto>> GetFilesInfoAsync(int idWell,
int idCategory, DateTime begin = default, DateTime end = default,
int skip = 0, int take = 32, CancellationToken token = default)
{
var query = db.Files
.Include(f => f.Author)
.Where(e => e.IdWell == idWell &&
e.IdCategory == idCategory);
query = query.Where(e => !e.IsDeleted);
if (begin != default)
query = query.Where(e => e.UploadDate >= begin);
if (end != default)
query = query.Where(e => e.UploadDate <= end);
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);
foreach (var item in entities)
{
var filePropertiesDto = item.Adapt<FileInfoDto>();
filePropertiesDto.AuthorName = item.Author.Name;
result.Items.Add(filePropertiesDto);
}
return result;
}
public async Task<FileInfoDto> GetFileInfoAsync(int fileId,
CancellationToken token = default)
{
var entity = await db.Files
.Include(f => f.Author)
.AsNoTracking()
.FirstOrDefaultAsync(f => f.Id == fileId, token)
.ConfigureAwait(false);
if (entity is null)
return null;
var dto = entity.Adapt<FileInfoDto>();
dto.AuthorName = entity.Author.Name;
return dto;
}
}
}