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

354 lines
14 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using AsbCloudApp.Data;
using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services
{
#nullable enable
/// <summary>
/// Сервис доступа к файлам
/// </summary>
public class FileService
{
private readonly IFileRepository fileRepository;
private readonly IFileStorageRepository fileStorageRepository;
/// <summary>
/// Сервис доступа к файлам
/// </summary>
/// <param name="fileRepository"></param>
/// <param name="fileStorageRepository"></param>
public FileService(IFileRepository fileRepository, IFileStorageRepository fileStorageRepository)
{
this.fileRepository = fileRepository;
this.fileStorageRepository = fileStorageRepository;
}
/// <summary>
/// переместить файл
/// </summary>
/// <param name="idWell"></param>
/// <param name="idUser"></param>
/// <param name="idCategory"></param>
/// <param name="destinationFileName"></param>
/// <param name="srcFilePath"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<FileInfoDto> MoveAsync(int idWell, int? idUser, int idCategory,
string destinationFileName, string srcFilePath, CancellationToken token = default)
{
destinationFileName = Path.GetFileName(destinationFileName);
srcFilePath = Path.GetFullPath(srcFilePath);
var fileSize = fileStorageRepository.GetLengthFile(srcFilePath);
//save info to db
var dto = new FileInfoDto {
IdWell = idWell,
IdAuthor = idUser,
IdCategory = idCategory,
Name = destinationFileName,
Size = fileSize
};
var fileId = await fileRepository.InsertAsync(dto, token)
.ConfigureAwait(false);
string filePath = fileStorageRepository.MakeFilePath(idWell, idCategory, destinationFileName, fileId);
fileStorageRepository.MoveFile(srcFilePath, filePath);
return await GetInfoAsync(fileId, token);
}
/// <summary>
/// Сохранить файл
/// </summary>
/// <param name="idWell"></param>
/// <param name="idUser"></param>
/// <param name="idCategory"></param>
/// <param name="fileFullName"></param>
/// <param name="fileStream"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<FileInfoDto> SaveAsync(int idWell, int? idUser, int idCategory,
string fileFullName, Stream fileStream, CancellationToken token)
{
//save info to db
var dto = new FileInfoDto
{
IdWell = idWell,
IdAuthor = idUser,
IdCategory = idCategory,
Name = Path.GetFileName(fileFullName),
Size = fileStream?.Length ?? 0
};
var fileId = await fileRepository.InsertAsync(dto, token)
.ConfigureAwait(false);
//save stream to disk
string filePath = fileStorageRepository.MakeFilePath(idWell, idCategory, fileFullName, fileId);
await fileStorageRepository.CopyFileAsync(filePath, fileStream, token);
return await GetInfoAsync(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>
/// <param name="idFile"></param>
/// <param name="token"></param>
/// <returns></returns>
public Task<int> DeleteAsync(int idFile, CancellationToken token)
=> DeleteAsync(new int[] { idFile }, token);
/// <summary>
/// удалить файлы
/// </summary>
/// <param name="ids"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<int> DeleteAsync(IEnumerable<int> ids, CancellationToken token)
{
if (ids is null || !ids.Any())
return 0;
var files = await fileRepository.DeleteAsync(ids, token).ConfigureAwait(false);
if (files is null || !files.Any())
return 0;
foreach (var file in files)
{
var fileName = GetUrl(file.IdWell, file.IdCategory, file.Id, Path.GetExtension(file.Name));
fileStorageRepository.DeleteFile(fileName);
}
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>
/// <param name="fileInfo"></param>
/// <returns></returns>
public string GetUrl(FileInfoDto fileInfo) =>
GetUrl(fileInfo.IdWell, fileInfo.IdCategory, fileInfo.Id, Path.GetExtension(fileInfo.Name));
/// <summary>
/// получить путь для скачивания
/// </summary>
/// <param name="idWell"></param>
/// <param name="idCategory"></param>
/// <param name="idFile"></param>
/// <param name="dotExtention"></param>
/// <returns></returns>
public string GetUrl(int idWell, int idCategory, int idFile, string dotExtention) =>
Path.Combine(fileStorageRepository.RootPath, idWell.ToString(), idCategory.ToString(), $"{idFile}{dotExtention}");
/// <summary>
/// пометить метку файла как удаленную
/// </summary>
/// <param name="idMark"></param>
/// <param name="token"></param>
/// <returns></returns>
public Task<int> MarkFileMarkAsDeletedAsync(int idMark,
CancellationToken token)
=> fileRepository.MarkFileMarkAsDeletedAsync(new int[] { idMark }, token);
/// <summary>
/// Инфо о файле
/// </summary>
/// <param name="idsFile"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<IEnumerable<FileInfoDto>> GetInfoByIdsAsync(IEnumerable<int> idsFile, CancellationToken token)
{
var result = await fileRepository.GetInfoByIdsAsync(idsFile, token).ConfigureAwait(false);
foreach (var entity in result)
{
var ext = Path.GetExtension(entity.Name);
var relativePath = GetUrl(entity.IdWell, entity.IdCategory, entity.Id, ext);
var fullPath = Path.GetFullPath(relativePath);
fileStorageRepository.FileExists(fullPath, relativePath);
}
return result;
}
/// <summary>
/// Получить список файлов в контейнере
/// </summary>
/// <param name="request"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<PaginationContainer<FileInfoDto>> GetInfosAsync(FileServiceRequest request, CancellationToken token)
=> await fileRepository.GetInfosAsync(request, token)
.ConfigureAwait(false);
/// <summary>
/// Пометить файл как удаленный
/// </summary>
/// <param name="idFile"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<int> MarkAsDeletedAsync(int idFile, CancellationToken token = default)
=> await fileRepository.MarkAsDeletedAsync(idFile, token)
.ConfigureAwait(false);
/// <summary>
/// добавить метку на файл
/// </summary>
/// <param name="fileMarkDto"></param>
/// <param name="idUser"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<int> CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token)
=> await fileRepository.CreateFileMarkAsync(fileMarkDto, idUser, token)
.ConfigureAwait(false);
/// <summary>
/// Получить запись по id
/// </summary>
/// <param name="id"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<FileInfoDto> GetOrDefaultAsync(int id, CancellationToken token)
=> await fileRepository.GetOrDefaultAsync(id, token)
.ConfigureAwait(false);
/// <summary>
/// получить инфо о файле по метке
/// </summary>
/// <param name="idMark"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<FileInfoDto> GetByMarkId(int idMark, CancellationToken token)
=> await fileRepository.GetByMarkId(idMark, token)
.ConfigureAwait(false);
/// <summary>
/// получить инфо о файле по метке
/// </summary>
/// <param name="idsMarks"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<int> MarkFileMarkAsDeletedAsync(IEnumerable<int> idsMarks, CancellationToken token)
=> await fileRepository.MarkFileMarkAsDeletedAsync(idsMarks, token)
.ConfigureAwait(false);
/// <summary>
/// Получение файлов по скважине
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<IEnumerable<FileInfoDto>> GetInfosByWellIdAsync(int idWell, CancellationToken token)
=> await fileRepository.GetInfosByWellIdAsync(new FileServiceRequest { IdWell = idWell, IsDeleted = false }, 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);
/// <summary>
/// Удаление всех файлов по скважине помеченных как удаленные
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<int> DeleteFilesFromDbMarkedDeletionByIdWell(int idWell, CancellationToken token)
{
var files = await fileRepository.GetInfosByWellIdAsync(
new FileServiceRequest
{
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.GetInfosByWellIdAsync(
new FileServiceRequest
{
IdWell = idWell
},
token);
var result = await Task.FromResult(fileStorageRepository.DeleteFilesNotExistStorage(idWell, files.Select(x => x.Id)));
return result;
}
/// <summary>
/// Вывод списка всех файлов из базы, для которых нет файла на диске
/// </summary>
/// <param name="idWell"></param>
/// <returns></returns>
public async Task<IEnumerable<FileInfoDto>> GetListFilesNotDisc(int idWell, CancellationToken token)
{
var files = await fileRepository.GetInfosByWellIdAsync(
new FileServiceRequest
{
IdWell = idWell
},
token);
var result = fileStorageRepository.GetListFilesNotDisc(idWell, files);
return result;
}
}
#nullable disable
}