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

360 lines
13 KiB
C#
Raw Normal View History

using AsbCloudApp.Data;
using AsbCloudApp.Exceptions;
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.Services
{
public class FileService : IFileService
{
public string RootPath { get; private set; }
private readonly IQueryable<AsbCloudDb.Model.FileInfo> dbSetConfigured;
private readonly IAsbCloudDbContext db;
2021-11-17 13:06:48 +05:00
public FileService(IAsbCloudDbContext db)
{
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);
}
2021-11-17 13:06:48 +05:00
public async Task<string> GetSharedUrlAsync(int idFileInfo, int idUser, IFileShareService fileShareService,
CancellationToken token)
{
var fileInfo = await GetInfoAsync(idFileInfo, token);
if (fileInfo is null)
return null;
2021-11-17 13:06:48 +05:00
var sharedUrl = await GetSharedUrlAsync(fileInfo, idUser, fileShareService, token);
return sharedUrl;
}
2021-11-17 13:06:48 +05:00
public async Task<string> GetSharedUrlAsync( FileInfoDto fileInfo, int idUser, IFileShareService fileShareService,
CancellationToken token)
{
var fileWebUrl = fileInfo.PublishInfo?.WebStorageFileUrl;
if (!string.IsNullOrEmpty(fileWebUrl))
return fileWebUrl;
var relativePath = GetUrl(fileInfo);
var sharedUrl = await fileShareService.PublishFileToCloudAsync(relativePath,
fileInfo.Name, token);
await SaveWeblinkToFileInfo(fileInfo.Id, idUser, sharedUrl, token);
return sharedUrl;
}
public async Task<FileInfoDto> MoveAsync(int idWell, int? idUser, int idCategory,
string destinationFileName, string srcFilePath, CancellationToken token = default)
2021-09-23 11:55:25 +05:00
{
destinationFileName = Path.GetFileName(destinationFileName);
srcFilePath = Path.GetFullPath(srcFilePath);
if (!File.Exists(srcFilePath))
throw new ArgumentInvalidException($"file {srcFilePath} doesn't exist", nameof(srcFilePath));
2021-09-23 11:55:25 +05:00
var sysFileInfo = new System.IO.FileInfo(srcFilePath);
2021-09-23 11:55:25 +05:00
//save info to db
var fileInfo = new AsbCloudDb.Model.FileInfo()
{
IdWell = idWell,
IdAuthor = idUser,
IdCategory = idCategory,
Name = destinationFileName,
UploadDate = DateTime.UtcNow,
2021-09-23 11:55:25 +05:00
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);
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
File.Move(srcFilePath, filePath);
2021-09-23 11:55:25 +05:00
return await GetInfoAsync(entry.Entity.Id, token);
2021-09-23 11:55:25 +05:00
}
public async Task<FileInfoDto> SaveAsync(int idWell, int? idUser, int idCategory,
string fileFullName, Stream fileStream, CancellationToken token)
{
2021-08-29 17:25:16 +05:00
//save info to db
var fileInfo = new AsbCloudDb.Model.FileInfo()
{
2021-08-29 17:25:16 +05:00
IdWell = idWell,
IdAuthor = idUser,
IdCategory = idCategory,
Name = Path.GetFileName(fileFullName),
UploadDate = DateTime.UtcNow,
2021-08-29 17:25:16 +05:00
IsDeleted = false,
Size = fileStream?.Length ?? 0
2021-08-29 17:25:16 +05:00
};
2021-08-29 17:25:16 +05:00
var entry = db.Files.Add(fileInfo);
2021-09-23 11:55:25 +05:00
await db.SaveChangesAsync(token).ConfigureAwait(false);
2021-08-29 17:25:16 +05:00
var fileId = entry.Entity.Id;
//save stream to disk
2021-09-23 11:55:25 +05:00
string filePath = MakeFilePath(idWell, idCategory, fileFullName, fileId);
2021-09-23 11:55:25 +05:00
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
2021-09-23 11:55:25 +05:00
using var newfileStream = new FileStream(filePath, FileMode.Create);
await fileStream.CopyToAsync(newfileStream, token).ConfigureAwait(false);
return await GetInfoAsync(entry.Entity.Id, token);
2021-08-29 17:25:16 +05:00
}
2021-09-23 11:55:25 +05:00
private string MakeFilePath(int idWell, int idCategory, string fileFullName, int fileId)
{
return Path.Combine(RootPath, $"{idWell}",
$"{idCategory}", $"{fileId}" + $"{Path.GetExtension(fileFullName)}");
}
2021-08-29 17:25:16 +05:00
public async Task<IEnumerable<FileInfoDto>> GetInfosByCategoryAsync(int idWell,
int idCategory, CancellationToken token)
2021-08-29 17:25:16 +05:00
{
var entities = await dbSetConfigured
.Where(e => e.IdWell == idWell && e.IdCategory == idCategory && e.IsDeleted == false)
2021-08-29 17:25:16 +05:00
.AsNoTracking()
.ToListAsync(token)
.ConfigureAwait(false);
var dtos = entities.Select(e => Convert(e));
2021-08-29 17:25:16 +05:00
return dtos;
}
2021-08-29 17:25:16 +05:00
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 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);
}
var dto = Convert(entity);
return dto;
}
2021-08-29 17:25:16 +05:00
public async Task<int> MarkAsDeletedAsync(int idFile,
CancellationToken token = default)
{
2021-08-29 17:25:16 +05:00
var fileInfo = await db.Files.FirstOrDefaultAsync(f => f.Id == idFile, token).ConfigureAwait(false);
if (fileInfo is null)
return 0;
fileInfo.IsDeleted = true;
2021-08-29 17:25:16 +05:00
return await db.SaveChangesAsync(token).ConfigureAwait(false);
}
public async Task<int> DeleteAsync(int idFile, CancellationToken token)
2021-08-29 17:25:16 +05:00
{
var fileInfo = await db.Files
.FirstOrDefaultAsync(f => f.Id == idFile, token)
.ConfigureAwait(false);
if (fileInfo is null)
return 0;
var fileName = GetUrl(fileInfo.Adapt<FileInfoDto>());
2021-08-29 17:25:16 +05:00
if (File.Exists(fileName))
File.Delete(fileName);
db.Files.Remove(fileInfo);
return await db.SaveChangesAsync(token).ConfigureAwait(false);
}
public string GetUrl(int idFile)
2021-08-29 17:25:16 +05:00
{
var fileInfo = db.Files
.FirstOrDefault(f => f.Id == idFile);
if (fileInfo is null)
return null;
return GetUrl(fileInfo.IdWell, fileInfo.IdCategory, fileInfo.Id, Path.GetExtension(fileInfo.Name));
}
public string GetUrl(FileInfoDto fileInfo) =>
GetUrl(fileInfo.IdWell, fileInfo.IdCategory, fileInfo.Id, Path.GetExtension(fileInfo.Name));
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;
db.FileMarks.Add(newFileMark);
return await db.SaveChangesAsync(token);
}
public async Task<int> MarkFileMarkAsDeletedAsync(int idMark,
CancellationToken token)
{
var fileMark = await db.FileMarks
.FirstOrDefaultAsync(m => m.Id == idMark, token)
.ConfigureAwait(false);
fileMark.IsDeleted = true;
return await db.SaveChangesAsync(token);
}
private async Task<int> SaveWeblinkToFileInfo(int idFileInfo, int idUser, string weblink,
CancellationToken token)
{
var fileInfo = await db.Files.FirstOrDefaultAsync(f => f.Id == idFileInfo, token)
.ConfigureAwait(false);
fileInfo.PublishInfo = new FilePublishInfo()
{
IdPublisher = idUser,
Date = DateTime.UtcNow,
WebStorageFileUrl = weblink
};
return await db.SaveChangesAsync(token).ConfigureAwait(false);
}
}
}