DD.WellWorkover.Cloud/AsbCloudInfrastructure/Repository/FileStorageRepository.cs

125 lines
3.7 KiB
C#
Raw Normal View History

using AsbCloudApp.Data;
using AsbCloudApp.Exceptions;
2022-10-06 14:37:03 +05:00
using AsbCloudApp.Repositories;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FileInfo = System.IO.FileInfo;
namespace AsbCloudInfrastructure.Repository
{
#nullable enable
public class FileStorageRepository : IFileStorageRepository
{
public string RootPath { get; private set; }
public FileStorageRepository()
{
RootPath = "files";
}
public async Task CopyFileAsync(string filePath, Stream fileStream, CancellationToken token)
{
CreateDirectory(filePath);
using var newfileStream = new FileStream(filePath, FileMode.Create);
await fileStream.CopyToAsync(newfileStream, token).ConfigureAwait(false);
}
public void DeleteFile(string fileName)
{
if (File.Exists(fileName))
File.Delete(fileName);
}
public long GetLengthFile(string srcFilePath)
{
if (!File.Exists(srcFilePath))
throw new ArgumentInvalidException($"file {srcFilePath} doesn't exist", nameof(srcFilePath));
var sysFileInfo = new FileInfo(srcFilePath);
return sysFileInfo.Length;
}
public void MoveFile(string srcFilePath, string filePath)
{
CreateDirectory(filePath);
File.Move(srcFilePath, filePath);
}
public bool FileExists(string fullPath, string fileName)
{
if (!File.Exists(fullPath))
throw new FileNotFoundException("not found", fileName);
return true;
}
public string MakeFilePath(int idWell, int idCategory, string fileFullName, int fileId)
{
return Path.Combine(RootPath, $"{idWell}",
$"{idCategory}", $"{fileId}" + $"{Path.GetExtension(fileFullName)}");
}
public int DeleteFilesNotExistStorage(int idWell, IEnumerable<int> idsFiles)
{
var allFilesPath = GetFilesPath(idWell);
var resutl = 0;
foreach (var filePath in allFilesPath)
{
var idFile = Path.GetFileNameWithoutExtension(filePath);
if (!idsFiles.Any(x => x.ToString() == idFile))
{
File.Delete(filePath);
resutl++;
}
}
return resutl;
}
public IEnumerable<FileInfoDto> GetListFilesNotDisc(int idWell, IEnumerable<FileInfoDto> files)
{
var resutl = new List<FileInfoDto>();
var idsFilesStorage = GetIdsFiles(idWell);
foreach (var file in files)
{
if (!idsFilesStorage.Any(x => x == file.Id))
resutl.Add(file);
}
return resutl;
}
private IEnumerable<int> GetIdsFiles(int idWell)
{
var result = new List<int>();
var allFilesPath = GetFilesPath(idWell);
foreach (var filePath in allFilesPath)
{
var idFileStr = Path.GetFileNameWithoutExtension(filePath);
result.Add(Convert.ToInt32(idFileStr));
}
return result;
}
private IEnumerable<string> GetFilesPath(int idWell)
{
var path = Path.Combine(RootPath, $"{idWell}");
return Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
}
private static void CreateDirectory(string filePath)
{
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
}
}
#nullable disable
}