Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Grand.Business.Storage - Code cleanup (ReSharper)
supportcc453c0ae598
diff --git a/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs b/src/Business/Grand.Business.Storage/Services/AmazonPictureService.csindex 1002798cd..d3bba65ad 100644--- a/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs+++ b/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs@@ -2,6 +2,7 @@using Amazon.Runtime;using Amazon.S3;using Amazon.S3.Model;+using Amazon.S3.Util;using Grand.Business.Core.Interfaces.Storage;using Grand.Data;using Grand.Domain.Media;@@ -11,221 +12,217 @@ using MediatR;using Microsoft.Extensions.Logging;using System.Net;-namespace Grand.Business.Storage.Services+namespace Grand.Business.Storage.Services;++/// <summary>+/// Picture service for Amazon+/// </summary>+public class AmazonPictureService : PictureService{- /// <summary>- /// Picture service for Amazon- /// </summary>- public class AmazonPictureService : PictureService+ #region Ctor++ public AmazonPictureService(IRepository<Picture> pictureRepository,+ ILogger<AmazonPictureService> logger,+ IMediator mediator,+ ICacheBase cacheBase,+ IMediaFileStore mediaFileStore,+ MediaSettings mediaSettings,+ StorageSettings storageSettings,+ AmazonConfig config)+ : base(pictureRepository,+ logger,+ mediator,+ cacheBase,+ mediaFileStore,+ mediaSettings,+ storageSettings){- #region Fields-- private readonly AmazonConfig _config;- private readonly string _bucketName;- private readonly string _distributionDomainName;- private bool _bucketExist = false;- private readonly IAmazonS3 _s3Client;-- #endregion-- #region Ctor-- public AmazonPictureService(IRepository<Picture> pictureRepository,- ILogger<AmazonPictureService> logger,- IMediator mediator,- ICacheBase cacheBase,- IMediaFileStore mediaFileStore,- MediaSettings mediaSettings,- StorageSettings storageSettings,- AmazonConfig config)- : base(pictureRepository,- logger,- mediator,- cacheBase,- mediaFileStore,- mediaSettings,- storageSettings)- {- _config = config;+ _config = config;++ //Arguments guard+ if (string.IsNullOrEmpty(_config.AmazonAwsAccessKeyId))+ throw new ArgumentNullException("AmazonAwsAccessKeyId");+ if (string.IsNullOrEmpty(_config.AmazonAwsSecretAccessKey))+ throw new ArgumentNullException("AmazonAwsSecretAccessKey");+ if (string.IsNullOrEmpty(_config.AmazonBucketName))+ throw new ArgumentNullException("AmazonBucketName");- //Arguments guard- if (string.IsNullOrEmpty(_config.AmazonAwsAccessKeyId))- throw new ArgumentNullException("AmazonAwsAccessKeyId");- if (string.IsNullOrEmpty(_config.AmazonAwsSecretAccessKey))- throw new ArgumentNullException("AmazonAwsSecretAccessKey");- if (string.IsNullOrEmpty(_config.AmazonBucketName))- throw new ArgumentNullException("AmazonBucketName");+ //Region guard+ var regionEndpoint = RegionEndpoint.GetBySystemName(_config.AmazonRegion);+ if (regionEndpoint.DisplayName == "Unknown")+ throw new NullReferenceException("specified Region is invalid");- //Region guard- var regionEndpoint = RegionEndpoint.GetBySystemName(_config.AmazonRegion);- if (regionEndpoint.DisplayName == "Unknown")- throw new NullReferenceException("specified Region is invalid");+ //Client guard+ _s3Client = new AmazonS3Client(_config.AmazonAwsAccessKeyId, _config.AmazonAwsSecretAccessKey, regionEndpoint);- //Client guard- _s3Client = new AmazonS3Client(_config.AmazonAwsAccessKeyId, _config.AmazonAwsSecretAccessKey, regionEndpoint);+ //Bucket guard+ _bucketName = _config.AmazonBucketName;- //Bucket guard- _bucketName = _config.AmazonBucketName;+ //Cloudfront distribution+ _distributionDomainName = _config.AmazonDistributionDomainName;+ }- //Cloudfront distribution- _distributionDomainName = _config.AmazonDistributionDomainName;+ #endregion- }+ #region Fields++ private readonly AmazonConfig _config;+ private readonly string _bucketName;+ private readonly string _distributionDomainName;+ private bool _bucketExist;+ private readonly IAmazonS3 _s3Client;- #endregion+ #endregion- #region Utilities+ #region Utilities- private async Task CheckBucketExists()+ private async Task CheckBucketExists()+ {+ if (!_bucketExist){- if (!_bucketExist)+ _bucketExist = await AmazonS3Util.DoesS3BucketExistV2Async(_s3Client, _bucketName);+ while (_bucketExist == false){+ var s3Region = S3Region.FindValue(_config.AmazonRegion);+ var putBucketRequest = new PutBucketRequest {+ BucketName = _bucketName,+ BucketRegion = s3Region+ };- _bucketExist = await Amazon.S3.Util.AmazonS3Util.DoesS3BucketExistV2Async(_s3Client, _bucketName);- while (_bucketExist == false)+ try{- var s3Region = S3Region.FindValue(_config.AmazonRegion);- var putBucketRequest = new PutBucketRequest {- BucketName = _bucketName,- BucketRegion = s3Region- };-- try- {- EnsureValidResponse(await _s3Client.PutBucketAsync(putBucketRequest), HttpStatusCode.OK);-- }- catch (AmazonS3Exception ex)- {- if (ex.ErrorCode == "BucketAlreadyOwnedByYou")- break;-- throw;- }- _bucketExist = await Amazon.S3.Util.AmazonS3Util.DoesS3BucketExistV2Async(_s3Client, _bucketName);+ EnsureValidResponse(await _s3Client.PutBucketAsync(putBucketRequest), HttpStatusCode.OK);}+ catch (AmazonS3Exception ex)+ {+ if (ex.ErrorCode == "BucketAlreadyOwnedByYou")+ break;++ throw;+ }++ _bucketExist = await AmazonS3Util.DoesS3BucketExistV2Async(_s3Client, _bucketName);}}+ }- /// <summary>- /// Ensure Every Response Will Have Expected HttpStatusCode- /// </summary>- /// <param name="actualResponse">Actual Response</param>- /// <param name="expectedHttpStatusCode">Expected Status Code</param>- private void EnsureValidResponse(AmazonWebServiceResponse actualResponse, HttpStatusCode expectedHttpStatusCode)- {- if (actualResponse.HttpStatusCode != expectedHttpStatusCode)- throw new Exception("Http Status Codes Aren't Consistent");- }+ /// <summary>+ /// Ensure Every Response Will Have Expected HttpStatusCode+ /// </summary>+ /// <param name="actualResponse">Actual Response</param>+ /// <param name="expectedHttpStatusCode">Expected Status Code</param>+ private void EnsureValidResponse(AmazonWebServiceResponse actualResponse, HttpStatusCode expectedHttpStatusCode)+ {+ if (actualResponse.HttpStatusCode != expectedHttpStatusCode)+ throw new Exception("Http Status Codes Aren't Consistent");+ }- /// <summary>- /// Delete picture thumbs- /// </summary>- /// <param name="picture">Picture</param>- protected override async Task DeletePictureThumbs(Picture picture)- {- await CheckBucketExists();+ /// <summary>+ /// Delete picture thumbs+ /// </summary>+ /// <param name="picture">Picture</param>+ protected override async Task DeletePictureThumbs(Picture picture)+ {+ await CheckBucketExists();- var listObjectsRequest = new ListObjectsV2Request {- BucketName = _bucketName,- Prefix = picture.Id- };- var listObjectsResponse = await _s3Client.ListObjectsV2Async(listObjectsRequest);+ var listObjectsRequest = new ListObjectsV2Request {+ BucketName = _bucketName,+ Prefix = picture.Id+ };+ var listObjectsResponse = await _s3Client.ListObjectsV2Async(listObjectsRequest);- foreach (var s3Object in listObjectsResponse.S3Objects)- {- EnsureValidResponse(await _s3Client.DeleteObjectAsync(_bucketName, s3Object.Key), HttpStatusCode.NoContent);- }- }+ foreach (var s3Object in listObjectsResponse.S3Objects)+ EnsureValidResponse(await _s3Client.DeleteObjectAsync(_bucketName, s3Object.Key), HttpStatusCode.NoContent);+ }- /// <summary>- /// Get picture (thumb) local path- /// </summary>- /// <param name="thumbFileName">Filename</param>- /// <returns>Local picture thumb path</returns>- protected override async Task<string> GetThumbPhysicalPath(string thumbFileName)- {- if (!await GeneratedThumbExists(thumbFileName))- return null;-- if (string.IsNullOrEmpty(_distributionDomainName))- {- return await Task.FromResult($"https://{_bucketName}.s3.amazonAws.com/{thumbFileName}");- }- return await Task.FromResult($"https://{_distributionDomainName}/{thumbFileName}");- }+ /// <summary>+ /// Get picture (thumb) local path+ /// </summary>+ /// <param name="thumbFileName">Filename</param>+ /// <returns>Local picture thumb path</returns>+ protected override async Task<string> GetThumbPhysicalPath(string thumbFileName)+ {+ if (!await GeneratedThumbExists(thumbFileName))+ return null;++ if (string.IsNullOrEmpty(_distributionDomainName))+ return await Task.FromResult($"https://{_bucketName}.s3.amazonAws.com/{thumbFileName}");+ return await Task.FromResult($"https://{_distributionDomainName}/{thumbFileName}");+ }- /// <summary>- /// Get a value indicating whether some file (thumb) already exists- /// </summary>- /// <param name="thumbFileName">Thumb file name</param>- /// <returns>Result</returns>- private Task<bool> GeneratedThumbExists(string thumbFileName)+ /// <summary>+ /// Get a value indicating whether some file (thumb) already exists+ /// </summary>+ /// <param name="thumbFileName">Thumb file name</param>+ /// <returns>Result</returns>+ private Task<bool> GeneratedThumbExists(string thumbFileName)+ {+ try{- try- {- var getObjectResponse = _s3Client.GetObjectAsync(_bucketName, thumbFileName).GetAwaiter().GetResult();- EnsureValidResponse(getObjectResponse, HttpStatusCode.OK);+ var getObjectResponse = _s3Client.GetObjectAsync(_bucketName, thumbFileName).GetAwaiter().GetResult();+ EnsureValidResponse(getObjectResponse, HttpStatusCode.OK);- return Task.FromResult(getObjectResponse.BucketName == _bucketName || getObjectResponse.Key == thumbFileName);- }- catch- {- return Task.FromResult(false);- }+ return Task.FromResult(+ getObjectResponse.BucketName == _bucketName || getObjectResponse.Key == thumbFileName);}- /// <summary>- /// Get picture (thumb) URL- /// </summary>- /// <param name="thumbFileName">Filename</param>- /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>- /// <returns>Local picture thumb path</returns>- protected override string GetThumbUrl(string thumbFileName, string storeLocation = null)+ catch{- return string.IsNullOrEmpty(_distributionDomainName) ? $"https://{_bucketName}.s3.amazonAws.com/{thumbFileName}" : $"https://{_distributionDomainName}/{thumbFileName}";+ return Task.FromResult(false);}+ }- /// <summary>- /// Save a value indicating whether some file (thumb) already exists- /// </summary>- /// <param name="thumbFileName">Thumb file name</param>- /// <param name="binary">Picture binary</param>- protected override Task SaveThumb(string thumbFileName, byte[] binary)- {- CheckBucketExists().Wait();+ /// <summary>+ /// Get picture (thumb) URL+ /// </summary>+ /// <param name="thumbFileName">Filename</param>+ /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>+ /// <returns>Local picture thumb path</returns>+ protected override string GetThumbUrl(string thumbFileName, string storeLocation = null)+ {+ return string.IsNullOrEmpty(_distributionDomainName)+ ? $"https://{_bucketName}.s3.amazonAws.com/{thumbFileName}"+ : $"https://{_distributionDomainName}/{thumbFileName}";+ }- using (Stream stream = new MemoryStream(binary))- {- var putObjectRequest = new PutObjectRequest {- BucketName = _bucketName,- InputStream = stream,- Key = thumbFileName,- StorageClass = S3StorageClass.Standard- };- _s3Client.PutObjectAsync(putObjectRequest).Wait();- }- _s3Client.MakeObjectPublicAsync(_bucketName, thumbFileName, true).Wait();- return Task.CompletedTask;- }+ /// <summary>+ /// Save a value indicating whether some file (thumb) already exists+ /// </summary>+ /// <param name="thumbFileName">Thumb file name</param>+ /// <param name="binary">Picture binary</param>+ protected override Task SaveThumb(string thumbFileName, byte[] binary)+ {+ CheckBucketExists().Wait();- /// <summary>- /// Clears pictures stored on Amazon S3, it won't affect Pictures stored in database- /// </summary>- public override async Task ClearThumbs()+ using (Stream stream = new MemoryStream(binary)){- await CheckBucketExists();-- var listObjectsRequest = new ListObjectsV2Request {- BucketName = _bucketName+ var putObjectRequest = new PutObjectRequest {+ BucketName = _bucketName,+ InputStream = stream,+ Key = thumbFileName,+ StorageClass = S3StorageClass.Standard};- var listObjectsResponse = await _s3Client.ListObjectsV2Async(listObjectsRequest);-- foreach (var s3Object in listObjectsResponse.S3Objects)- {- EnsureValidResponse(await _s3Client.DeleteObjectAsync(_bucketName, s3Object.Key), HttpStatusCode.NoContent);- }+ _s3Client.PutObjectAsync(putObjectRequest).Wait();}- #endregion+ _s3Client.MakeObjectPublicAsync(_bucketName, thumbFileName, true).Wait();+ return Task.CompletedTask;}++ /// <summary>+ /// Clears pictures stored on Amazon S3, it won't affect Pictures stored in database+ /// </summary>+ public override async Task ClearThumbs()+ {+ await CheckBucketExists();++ var listObjectsRequest = new ListObjectsV2Request {+ BucketName = _bucketName+ };+ var listObjectsResponse = await _s3Client.ListObjectsV2Async(listObjectsRequest);++ foreach (var s3Object in listObjectsResponse.S3Objects)+ EnsureValidResponse(await _s3Client.DeleteObjectAsync(_bucketName, s3Object.Key), HttpStatusCode.NoContent);+ }++ #endregion}\ No newline at end of filediff --git a/src/Business/Grand.Business.Storage/Services/AzurePictureService.cs b/src/Business/Grand.Business.Storage/Services/AzurePictureService.csindex e0dcf0a4f..9ee8bb017 100644--- a/src/Business/Grand.Business.Storage/Services/AzurePictureService.cs+++ b/src/Business/Grand.Business.Storage/Services/AzurePictureService.cs@@ -9,130 +9,126 @@ using Grand.Infrastructure.Configuration;using MediatR;using Microsoft.Extensions.Logging;-namespace Grand.Business.Storage.Services+namespace Grand.Business.Storage.Services;++/// <summary>+/// Picture service for Windows Azure+/// </summary>+public class AzurePictureService : PictureService{+ #region Ctor++ public AzurePictureService(IRepository<Picture> pictureRepository,+ ILogger<AzurePictureService> logger,+ IMediator mediator,+ ICacheBase cacheBase,+ IMediaFileStore mediaFileStore,+ MediaSettings mediaSettings,+ StorageSettings storageSettings,+ AzureConfig config,+ IMimeMappingService mimeMappingService+ )+ : base(pictureRepository,+ logger,+ mediator,+ cacheBase,+ mediaFileStore,+ mediaSettings,+ storageSettings)+ {+ _config = config;+ _mimeMappingService = mimeMappingService;++ if (string.IsNullOrEmpty(_config.AzureBlobStorageConnectionString))+ throw new Exception("Azure connection string for BLOB is not specified");+ if (string.IsNullOrEmpty(_config.AzureBlobStorageContainerName))+ throw new Exception("Azure container name for BLOB is not specified");+ if (string.IsNullOrEmpty(_config.AzureBlobStorageEndPoint))+ throw new Exception("Azure end point for BLOB is not specified");++ _container = new BlobContainerClient(_config.AzureBlobStorageConnectionString,+ _config.AzureBlobStorageContainerName);+ }++ #endregion++ #region Fields++ private static BlobContainerClient _container;+ private readonly AzureConfig _config;+ private readonly IMimeMappingService _mimeMappingService;++ #endregion++ #region Utilities++ /// <summary>+ /// Delete picture thumbs+ /// </summary>+ /// <param name="picture">Picture</param>+ protected override async Task DeletePictureThumbs(Picture picture)+ {+ var filter = $"{picture.Id}";+ var blobs = _container.GetBlobs(BlobTraits.All, BlobStates.All, filter);++ foreach (var blob in blobs) await _container.DeleteBlobAsync(blob.Name);+ }++ /// <summary>+ /// Get picture (thumb) local path+ /// </summary>+ /// <param name="thumbFileName">Filename</param>+ /// <returns>Local picture thumb path</returns>+ protected override async Task<string> GetThumbPhysicalPath(string thumbFileName)+ {+ var thumbFilePath =+ $"{_config.AzureBlobStorageEndPoint}{_config.AzureBlobStorageContainerName}/{thumbFileName}";+ var blobClient = _container.GetBlobClient(thumbFileName);+ bool exists = await blobClient.ExistsAsync();+ return exists ? thumbFilePath : string.Empty;+ }+/// <summary>- /// Picture service for Windows Azure+ /// Get picture (thumb) URL/// </summary>- public class AzurePictureService : PictureService+ /// <param name="thumbFileName">Filename</param>+ /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>+ /// <returns>Local picture thumb path</returns>+ protected override string GetThumbUrl(string thumbFileName, string storeLocation = null){- #region Fields-- private static BlobContainerClient _container = null;- private readonly AzureConfig _config;- private readonly IMimeMappingService _mimeMappingService;-- #endregion-- #region Ctor-- public AzurePictureService(IRepository<Picture> pictureRepository,- ILogger<AzurePictureService> logger,- IMediator mediator,- ICacheBase cacheBase,- IMediaFileStore mediaFileStore,- MediaSettings mediaSettings,- StorageSettings storageSettings,- AzureConfig config,- IMimeMappingService mimeMappingService- )- : base(pictureRepository,- logger,- mediator,- cacheBase,- mediaFileStore,- mediaSettings,- storageSettings)- {- _config = config;- _mimeMappingService = mimeMappingService;-- if (string.IsNullOrEmpty(_config.AzureBlobStorageConnectionString))- throw new Exception("Azure connection string for BLOB is not specified");- if (string.IsNullOrEmpty(_config.AzureBlobStorageContainerName))- throw new Exception("Azure container name for BLOB is not specified");- if (string.IsNullOrEmpty(_config.AzureBlobStorageEndPoint))- throw new Exception("Azure end point for BLOB is not specified");-- _container = new BlobContainerClient(_config.AzureBlobStorageConnectionString, _config.AzureBlobStorageContainerName);-- }-- #endregion-- #region Utilities-- /// <summary>- /// Delete picture thumbs- /// </summary>- /// <param name="picture">Picture</param>- protected override async Task DeletePictureThumbs(Picture picture)- {- var filter = $"{picture.Id}";- var blobs = _container.GetBlobs(BlobTraits.All, BlobStates.All, filter);-- foreach (var blob in blobs)- {- await _container.DeleteBlobAsync(blob.Name);- }- }-- /// <summary>- /// Get picture (thumb) local path- /// </summary>- /// <param name="thumbFileName">Filename</param>- /// <returns>Local picture thumb path</returns>- protected override async Task<string> GetThumbPhysicalPath(string thumbFileName)- {- var thumbFilePath = $"{_config.AzureBlobStorageEndPoint}{_config.AzureBlobStorageContainerName}/{thumbFileName}";- var blobClient = _container.GetBlobClient(thumbFileName);- bool exists = await blobClient.ExistsAsync();- return exists? thumbFilePath : string.Empty;- }-- /// <summary>- /// Get picture (thumb) URL- /// </summary>- /// <param name="thumbFileName">Filename</param>- /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>- /// <returns>Local picture thumb path</returns>- protected override string GetThumbUrl(string thumbFileName, string storeLocation = null)- {- var url = _config.AzureBlobStorageEndPoint + _config.AzureBlobStorageContainerName + "/";- url += thumbFileName;- return url;- }-- /// <summary>- /// Save a value indicating whether some file (thumb) already exists- /// </summary>- /// <param name="thumbFileName">Thumb file name</param>- /// <param name="binary">Picture binary</param>- protected override Task SaveThumb(string thumbFileName, byte[] binary)- {-- Stream stream = new MemoryStream(binary);- _container.UploadBlob(thumbFileName, stream);-- //Update content type and other properties- var contentType = _mimeMappingService.Map(thumbFileName);- var blobClient = _container.GetBlobClient(thumbFileName);- BlobProperties properties = blobClient.GetProperties();- BlobHttpHeaders blobHttpHeaders = new BlobHttpHeaders {- // Set the MIME ContentType every time the properties- // are updated or the field will be cleared- ContentType = contentType,- // Populate remaining headers with- // the pre-existing properties- CacheControl = properties.CacheControl,- ContentDisposition = properties.ContentDisposition,- ContentEncoding = properties.ContentEncoding,- ContentHash = properties.ContentHash- };- blobClient.SetHttpHeaders(blobHttpHeaders);- return Task.CompletedTask;- }-- #endregion+ var url = _config.AzureBlobStorageEndPoint + _config.AzureBlobStorageContainerName + "/";+ url += thumbFileName;+ return url;}-}++ /// <summary>+ /// Save a value indicating whether some file (thumb) already exists+ /// </summary>+ /// <param name="thumbFileName">Thumb file name</param>+ /// <param name="binary">Picture binary</param>+ protected override Task SaveThumb(string thumbFileName, byte[] binary)+ {+ Stream stream = new MemoryStream(binary);+ _container.UploadBlob(thumbFileName, stream);++ //Update content type and other properties+ var contentType = _mimeMappingService.Map(thumbFileName);+ var blobClient = _container.GetBlobClient(thumbFileName);+ BlobProperties properties = blobClient.GetProperties();+ var blobHttpHeaders = new BlobHttpHeaders {+ // Set the MIME ContentType every time the properties+ // are updated or the field will be cleared+ ContentType = contentType,+ // Populate remaining headers with+ // the pre-existing properties+ CacheControl = properties.CacheControl,+ ContentDisposition = properties.ContentDisposition,+ ContentEncoding = properties.ContentEncoding,+ ContentHash = properties.ContentHash+ };+ blobClient.SetHttpHeaders(blobHttpHeaders);+ return Task.CompletedTask;+ }++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Storage/Services/DefaultMediaFileStore.cs b/src/Business/Grand.Business.Storage/Services/DefaultMediaFileStore.csindex f110b83bb..a1dcf5c2e 100644--- a/src/Business/Grand.Business.Storage/Services/DefaultMediaFileStore.cs+++ b/src/Business/Grand.Business.Storage/Services/DefaultMediaFileStore.cs@@ -3,95 +3,100 @@using Grand.Business.Core.Interfaces.Storage;using Microsoft.Extensions.FileProviders.Physical;-namespace Grand.Business.Storage.Services+namespace Grand.Business.Storage.Services;++public class DefaultMediaFileStore : IMediaFileStore{- public class DefaultMediaFileStore : IMediaFileStore- {- private readonly IFileStore _fileStore;-- public DefaultMediaFileStore(- IFileStore fileStore)- {- _fileStore = fileStore;- }--- public virtual Task<IFileStoreEntry> GetFileInfo(string path)- {- return _fileStore.GetFileInfo(path);- }-- public virtual IFileStoreEntry GetDirectoryInfo(string path)- {- return _fileStore.GetDirectoryInfo(path);- }- public virtual Task<PhysicalDirectoryInfo> GetPhysicalDirectoryInfo(string directoryPath)- {- return _fileStore.GetPhysicalDirectoryInfo(directoryPath);- }-- public virtual IList<IFileStoreEntry> GetDirectoryContent(string path = null, bool includeSubDirectories = false, bool listDirectories = true, bool listFiles = true)- {- return _fileStore.GetDirectoryContent(path, includeSubDirectories, listDirectories, listFiles);- }-- public virtual bool TryCreateDirectory(string path)- {- return _fileStore.TryCreateDirectory(path);- }-- public virtual Task<bool> TryRenameDirectory(string path, string newpath)- {- return _fileStore.TryRenameDirectory(path, newpath);- }-- public virtual async Task<bool> TryDeleteFile(string path)- {- var result = await _fileStore.TryDeleteFile(path);-- return result;- }-- public virtual async Task<bool> TryDeleteDirectory(string path)- {- var result = await _fileStore.TryDeleteDirectory(path);- return result;- }-- public virtual async Task MoveFile(string oldPath, string newPath)- {- await _fileStore.MoveFile(oldPath, newPath);- }-- public virtual Task CopyFile(string srcPath, string dstPath)- {- return _fileStore.CopyFile(srcPath, dstPath);- }- public virtual Task RenameFile(string file, string newName)- {- return _fileStore.RenameFile(file, newName);- }- public virtual Task<Stream> GetFileStream(string path)- {- return _fileStore.GetFileStream(path);- }-- public virtual Task<Stream> GetFileStream(IFileStoreEntry fileStoreEntry)- {- return _fileStore.GetFileStream(fileStoreEntry);- }-- public virtual async Task<string> CreateFileFromStream(string path, Stream inputStream, bool overwrite = false)- {- return await _fileStore.CreateFileFromStream(path, inputStream, overwrite);- }- public virtual Task<string> ReadAllText(string path)- {- return _fileStore.ReadAllText(path);- }- public virtual Task WriteAllText(string path, string text)- {- return _fileStore.WriteAllText(path, text);- }- }-}+ private readonly IFileStore _fileStore;++ public DefaultMediaFileStore(+ IFileStore fileStore)+ {+ _fileStore = fileStore;+ }+++ public virtual Task<IFileStoreEntry> GetFileInfo(string path)+ {+ return _fileStore.GetFileInfo(path);+ }++ public virtual IFileStoreEntry GetDirectoryInfo(string path)+ {+ return _fileStore.GetDirectoryInfo(path);+ }++ public virtual Task<PhysicalDirectoryInfo> GetPhysicalDirectoryInfo(string directoryPath)+ {+ return _fileStore.GetPhysicalDirectoryInfo(directoryPath);+ }++ public virtual IList<IFileStoreEntry> GetDirectoryContent(string path = null, bool includeSubDirectories = false,+ bool listDirectories = true, bool listFiles = true)+ {+ return _fileStore.GetDirectoryContent(path, includeSubDirectories, listDirectories, listFiles);+ }++ public virtual bool TryCreateDirectory(string path)+ {+ return _fileStore.TryCreateDirectory(path);+ }++ public virtual Task<bool> TryRenameDirectory(string path, string newpath)+ {+ return _fileStore.TryRenameDirectory(path, newpath);+ }++ public virtual async Task<bool> TryDeleteFile(string path)+ {+ var result = await _fileStore.TryDeleteFile(path);++ return result;+ }++ public virtual async Task<bool> TryDeleteDirectory(string path)+ {+ var result = await _fileStore.TryDeleteDirectory(path);+ return result;+ }++ public virtual async Task MoveFile(string oldPath, string newPath)+ {+ await _fileStore.MoveFile(oldPath, newPath);+ }++ public virtual Task CopyFile(string srcPath, string dstPath)+ {+ return _fileStore.CopyFile(srcPath, dstPath);+ }++ public virtual Task RenameFile(string file, string newName)+ {+ return _fileStore.RenameFile(file, newName);+ }++ public virtual Task<Stream> GetFileStream(string path)+ {+ return _fileStore.GetFileStream(path);+ }++ public virtual Task<Stream> GetFileStream(IFileStoreEntry fileStoreEntry)+ {+ return _fileStore.GetFileStream(fileStoreEntry);+ }++ public virtual async Task<string> CreateFileFromStream(string path, Stream inputStream, bool overwrite = false)+ {+ return await _fileStore.CreateFileFromStream(path, inputStream, overwrite);+ }++ public virtual Task<string> ReadAllText(string path)+ {+ return _fileStore.ReadAllText(path);+ }++ public virtual Task WriteAllText(string path, string text)+ {+ return _fileStore.WriteAllText(path, text);+ }+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Storage/Services/DownloadService.cs b/src/Business/Grand.Business.Storage/Services/DownloadService.csindex 2a1eb5928..447e28ad1 100644--- a/src/Business/Grand.Business.Storage/Services/DownloadService.cs+++ b/src/Business/Grand.Business.Storage/Services/DownloadService.cs@@ -4,133 +4,132 @@ using Grand.Domain.Media;using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Storage.Services+namespace Grand.Business.Storage.Services;++/// <summary>+/// Download service+/// </summary>+public class DownloadService : IDownloadService{+ #region Ctor++ /// <summary>+ /// Ctor+ /// </summary>+ /// <param name="downloadRepository">Download repository</param>+ /// <param name="storeFilesContext">Store Files Context</param>+ /// <param name="mediator">Mediator</param>+ public DownloadService(IRepository<Download> downloadRepository,+ IStoreFilesContext storeFilesContext,+ IMediator mediator)+ {+ _downloadRepository = downloadRepository;+ _storeFilesContext = storeFilesContext;+ _mediator = mediator;+ }++ #endregion++ #region Fields++ private readonly IRepository<Download> _downloadRepository;+ private readonly IStoreFilesContext _storeFilesContext;+ private readonly IMediator _mediator;++ #endregion++ #region Methods++ /// <summary>+ /// Gets a download+ /// </summary>+ /// <param name="downloadId">Download identifier</param>+ /// <returns>Download</returns>+ public virtual async Task<Download> GetDownloadById(string downloadId)+ {+ if (string.IsNullOrEmpty(downloadId))+ return null;++ var download = await _downloadRepository.GetByIdAsync(downloadId);+ if (download is { UseDownloadUrl: false })+ download.DownloadBinary = await DownloadAsBytes(download.DownloadObjectId);++ return download;+ }++ protected virtual async Task<byte[]> DownloadAsBytes(string objectId)+ {+ var binary = await _storeFilesContext.BucketDownload(objectId);+ return binary;+ }++ /// <summary>+ /// Gets a download by GUID+ /// </summary>+ /// <param name="downloadGuid">Download GUID</param>+ /// <returns>Download</returns>+ public virtual async Task<Download> GetDownloadByGuid(Guid downloadGuid)+ {+ if (downloadGuid == Guid.Empty)+ return null;++ var query = from o in _downloadRepository.Table+ where o.DownloadGuid == downloadGuid+ select o;++ var order = query.FirstOrDefault();+ if (order is { UseDownloadUrl: false })+ order.DownloadBinary = await DownloadAsBytes(order.DownloadObjectId);++ return await Task.FromResult(order);+ }++ /// <summary>+ /// Inserts a download+ /// </summary>+ /// <param name="download">Download</param>+ public virtual async Task InsertDownload(Download download)+ {+ ArgumentNullException.ThrowIfNull(download);+ if (!download.UseDownloadUrl)+ download.DownloadObjectId =+ await _storeFilesContext.BucketUploadFromBytes(download.Filename, download.DownloadBinary);++ download.DownloadBinary = null;+ await _downloadRepository.InsertAsync(download);++ await _mediator.EntityInserted(download);+ }++ /// <summary>+ /// Updates the download+ /// </summary>+ /// <param name="download">Download</param>+ public virtual async Task UpdateDownload(Download download)+ {+ ArgumentNullException.ThrowIfNull(download);++ await _downloadRepository.UpdateAsync(download);++ await _mediator.EntityUpdated(download);+ }+/// <summary>- /// Download service+ /// Deletes a download/// </summary>- public class DownloadService : IDownloadService+ /// <param name="download">Download</param>+ public virtual async Task DeleteDownload(Download download){- #region Fields-- private readonly IRepository<Download> _downloadRepository;- private readonly IStoreFilesContext _storeFilesContext;- private readonly IMediator _mediator;-- #endregion-- #region Ctor-- /// <summary>- /// Ctor- /// </summary>- /// <param name="downloadRepository">Download repository</param>- /// <param name="storeFilesContext">Store Files Context</param>- /// <param name="mediator">Mediator</param>- public DownloadService(IRepository<Download> downloadRepository,- IStoreFilesContext storeFilesContext,- IMediator mediator)- {- _downloadRepository = downloadRepository;- _storeFilesContext = storeFilesContext;- _mediator = mediator;- }-- #endregion-- #region Methods-- /// <summary>- /// Gets a download- /// </summary>- /// <param name="downloadId">Download identifier</param>- /// <returns>Download</returns>- public virtual async Task<Download> GetDownloadById(string downloadId)- {- if (string.IsNullOrEmpty(downloadId))- return null;-- var download = await _downloadRepository.GetByIdAsync(downloadId);- if (download is { UseDownloadUrl: false })- download.DownloadBinary = await DownloadAsBytes(download.DownloadObjectId);-- return download;- }-- protected virtual async Task<byte[]> DownloadAsBytes(string objectId)- {- var binary = await _storeFilesContext.BucketDownload(objectId);- return binary;- }- /// <summary>- /// Gets a download by GUID- /// </summary>- /// <param name="downloadGuid">Download GUID</param>- /// <returns>Download</returns>- public virtual async Task<Download> GetDownloadByGuid(Guid downloadGuid)- {- if (downloadGuid == Guid.Empty)- return null;-- var query = from o in _downloadRepository.Table- where o.DownloadGuid == downloadGuid- select o;-- var order = query.FirstOrDefault();- if (order is { UseDownloadUrl: false })- order.DownloadBinary = await DownloadAsBytes(order.DownloadObjectId);-- return await Task.FromResult(order);- }-- /// <summary>- /// Inserts a download- /// </summary>- /// <param name="download">Download</param>- public virtual async Task InsertDownload(Download download)- {- ArgumentNullException.ThrowIfNull(download);- if (!download.UseDownloadUrl)- {- download.DownloadObjectId = await _storeFilesContext.BucketUploadFromBytes(download.Filename, download.DownloadBinary);- }-- download.DownloadBinary = null;- await _downloadRepository.InsertAsync(download);-- await _mediator.EntityInserted(download);- }-- /// <summary>- /// Updates the download- /// </summary>- /// <param name="download">Download</param>- public virtual async Task UpdateDownload(Download download)- {- ArgumentNullException.ThrowIfNull(download);-- await _downloadRepository.UpdateAsync(download);-- await _mediator.EntityUpdated(download);- }-- /// <summary>- /// Deletes a download- /// </summary>- /// <param name="download">Download</param>- public virtual async Task DeleteDownload(Download download)- {- ArgumentNullException.ThrowIfNull(download);-- await _downloadRepository.DeleteAsync(download);-- //delete from bucket- if(!string.IsNullOrEmpty(download.DownloadObjectId))- await _storeFilesContext.BucketDelete(download.DownloadObjectId);-- await _mediator.EntityDeleted(download);- }-- #endregion+ ArgumentNullException.ThrowIfNull(download);++ await _downloadRepository.DeleteAsync(download);++ //delete from bucket+ if (!string.IsNullOrEmpty(download.DownloadObjectId))+ await _storeFilesContext.BucketDelete(download.DownloadObjectId);++ await _mediator.EntityDeleted(download);}-}++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Storage/Services/FileSystemStore.cs b/src/Business/Grand.Business.Storage/Services/FileSystemStore.csindex 0412b1072..fabcd8f06 100644--- a/src/Business/Grand.Business.Storage/Services/FileSystemStore.cs+++ b/src/Business/Grand.Business.Storage/Services/FileSystemStore.cs@@ -3,71 +3,72 @@using Grand.Business.Core.Interfaces.Storage;using Microsoft.Extensions.FileProviders.Physical;-namespace Grand.Business.Storage.Services+namespace Grand.Business.Storage.Services;++public class FileSystemStore : IFileStore{- public class FileSystemStore : IFileStore+ private readonly string _fileSystemPath;++ public FileSystemStore(string fileSystemPath)+ {+ _fileSystemPath = Path.GetFullPath(fileSystemPath);+ }++ public Task<IFileStoreEntry> GetFileInfo(string path)+ {+ var physicalPath = GetPhysicalPath(path);++ var fileInfo = new PhysicalFileInfo(new FileInfo(physicalPath));++ return Task.FromResult<IFileStoreEntry>(fileInfo.Exists ? new FileSystemStoreEntry(path, fileInfo) : null);+ }++ public IFileStoreEntry GetDirectoryInfo(string path)+ {+ var physicalPath = GetPhysicalPath(path);++ var directoryInfo = new PhysicalDirectoryInfo(new DirectoryInfo(physicalPath));++ return directoryInfo.Exists ? new FileSystemStoreEntry(path, directoryInfo) : null;+ }++ public Task<PhysicalDirectoryInfo> GetPhysicalDirectoryInfo(string directoryPath)+ {+ var physicalPath = GetPhysicalPath(directoryPath);++ var directoryInfo = new PhysicalDirectoryInfo(new DirectoryInfo(physicalPath));++ return directoryInfo.Exists ? Task.FromResult(directoryInfo) : Task.FromResult<PhysicalDirectoryInfo>(null);+ }++ public IList<IFileStoreEntry> GetDirectoryContent(string path = null, bool includeSubDirectories = false,+ bool listDirectories = true, bool listFiles = true){- private readonly string _fileSystemPath;-- public FileSystemStore(string fileSystemPath)- {- _fileSystemPath = Path.GetFullPath(fileSystemPath);- }-- public Task<IFileStoreEntry> GetFileInfo(string path)- {- var physicalPath = GetPhysicalPath(path);-- var fileInfo = new PhysicalFileInfo(new FileInfo(physicalPath));-- return Task.FromResult<IFileStoreEntry>(fileInfo.Exists ? new FileSystemStoreEntry(path, fileInfo) : null);- }-- public IFileStoreEntry GetDirectoryInfo(string path)- {- var physicalPath = GetPhysicalPath(path);-- var directoryInfo = new PhysicalDirectoryInfo(new DirectoryInfo(physicalPath));-- return directoryInfo.Exists ? new FileSystemStoreEntry(path, directoryInfo) : null;- }-- public Task<PhysicalDirectoryInfo> GetPhysicalDirectoryInfo(string directoryPath)- {- var physicalPath = GetPhysicalPath(directoryPath);-- var directoryInfo = new PhysicalDirectoryInfo(new DirectoryInfo(physicalPath));-- return directoryInfo.Exists ? Task.FromResult(directoryInfo) : Task.FromResult<PhysicalDirectoryInfo>(null);- }- public IList<IFileStoreEntry> GetDirectoryContent(string path = null, bool includeSubDirectories = false, bool listDirectories = true, bool listFiles = true)- {- var physicalPath = GetPhysicalPath(path);- var results = new List<IFileStoreEntry>();-- if (!Directory.Exists(physicalPath))- {- return results.ToList();- }-- // Add directories.- if (listDirectories)- results.AddRange(- Directory- .GetDirectories(physicalPath, "*", includeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)- .Select(f =>- {- var fileSystemInfo = new PhysicalDirectoryInfo(new DirectoryInfo(f));- var fileRelativePath = f[_fileSystemPath.Length..];- var filePath = this.NormalizePath(fileRelativePath);- return new FileSystemStoreEntry(filePath, fileSystemInfo);- }));-- // Add files.- if (listFiles)- results.AddRange(+ var physicalPath = GetPhysicalPath(path);+ var results = new List<IFileStoreEntry>();++ if (!Directory.Exists(physicalPath)) return results.ToList();++ // Add directories.+ if (listDirectories)+ results.AddRange(Directory- .GetFiles(physicalPath, "*", includeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)+ .GetDirectories(physicalPath, "*",+ includeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)+ .Select(f =>+ {+ var fileSystemInfo = new PhysicalDirectoryInfo(new DirectoryInfo(f));+ var fileRelativePath = f[_fileSystemPath.Length..];+ var filePath = this.NormalizePath(fileRelativePath);+ return new FileSystemStoreEntry(filePath, fileSystemInfo);+ }));++ // Add files.+ if (listFiles)+ results.AddRange(+ Directory+ .GetFiles(physicalPath, "*",+ includeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).Select(f =>{var fileSystemInfo = new PhysicalFileInfo(new FileInfo(f));@@ -76,232 +77,188 @@ namespace Grand.Business.Storage.Servicesreturn new FileSystemStoreEntry(filePath, fileSystemInfo);}));- return results.ToList();- }+ return results.ToList();+ }++ public bool TryCreateDirectory(string path)+ {+ var physicalPath = GetPhysicalPath(path);++ if (File.Exists(physicalPath))+ throw new Exception($"Cannot create directory because the path '{path}' already exists and is a file.");++ if (Directory.Exists(physicalPath)) return false;++ Directory.CreateDirectory(physicalPath);++ return true;+ }++ public Task<bool> TryRenameDirectory(string path, string newName)+ {+ var physicalPath = GetPhysicalPath(path);++ if (File.Exists(physicalPath))+ throw new Exception($"Cannot create directory because the path '{path}' already exists and is a file.");++ if (!Directory.Exists(physicalPath)) return Task.FromResult(false);+ var directoryInfo = new DirectoryInfo(physicalPath);++ var newphysicalPath = GetPhysicalPath(Path.Combine(directoryInfo.Parent.FullName, newName));++ if (Directory.Exists(newphysicalPath)) return Task.FromResult(false);+ directoryInfo.MoveTo(newphysicalPath);++ return Task.FromResult(true);+ }++ public Task<bool> TryDeleteFile(string path)+ {+ var physicalPath = GetPhysicalPath(path);++ if (!File.Exists(physicalPath)) return Task.FromResult(false);++ File.Delete(physicalPath);++ return Task.FromResult(true);+ }++ public Task<bool> TryDeleteDirectory(string path)+ {+ var physicalPath = GetPhysicalPath(path);++ if (!Directory.Exists(physicalPath)) return Task.FromResult(false);++ Directory.Delete(physicalPath, true);++ return Task.FromResult(true);+ }++ public Task MoveFile(string oldPath, string newPath)+ {+ var physicalOldPath = GetPhysicalPath(oldPath);++ if (!File.Exists(physicalOldPath))+ throw new Exception($"Cannot move file '{oldPath}' because it does not exist.");++ var physicalNewPath = GetPhysicalPath(newPath);++ if (File.Exists(physicalNewPath) || Directory.Exists(physicalNewPath))+ throw new Exception($"Cannot move file because the new path '{newPath}' already exists.");++ File.Move(physicalOldPath, physicalNewPath);- public bool TryCreateDirectory(string path)- {- var physicalPath = GetPhysicalPath(path);-- if (File.Exists(physicalPath))- throw new Exception($"Cannot create directory because the path '{path}' already exists and is a file.");+ return Task.CompletedTask;+ }- if (Directory.Exists(physicalPath))- {- return false;- }-- Directory.CreateDirectory(physicalPath);+ public async Task CopyFile(string srcPath, string dstPath)+ {+ var physicalSrcPath = GetPhysicalPath(srcPath);- return true;- }- public Task<bool> TryRenameDirectory(string path, string newName)- {- var physicalPath = GetPhysicalPath(path);+ if (!File.Exists(physicalSrcPath)) throw new Exception($"The file '{srcPath}' does not exist.");+ var file = await GetFileInfo(srcPath);+ var physicalDstPath = GetPhysicalPath(Path.Combine(dstPath));- if (File.Exists(physicalPath))- {- throw new Exception($"Cannot create directory because the path '{path}' already exists and is a file.");- }-- if (!Directory.Exists(physicalPath))- {- return Task.FromResult(false);- }- var directoryInfo = new DirectoryInfo(physicalPath);-- var newphysicalPath = GetPhysicalPath(Path.Combine(directoryInfo.Parent.FullName, newName));-- if (Directory.Exists(newphysicalPath))- {- return Task.FromResult(false);- }- directoryInfo.MoveTo(newphysicalPath);+ if (File.Exists(physicalDstPath) || Directory.Exists(physicalDstPath))+ throw new Exception($"Cannot copy file because the destination path '{dstPath}' already exists.");- return Task.FromResult(true);- }+ File.Copy(physicalSrcPath, physicalDstPath);+ }- public Task<bool> TryDeleteFile(string path)- {- var physicalPath = GetPhysicalPath(path);-- if (!File.Exists(physicalPath))- {- return Task.FromResult(false);- }-- File.Delete(physicalPath);-- return Task.FromResult(true);- }-- public Task<bool> TryDeleteDirectory(string path)- {- var physicalPath = GetPhysicalPath(path);-- if (!Directory.Exists(physicalPath))- {- return Task.FromResult(false);- }-- Directory.Delete(physicalPath, recursive: true);-- return Task.FromResult(true);- }-- public Task MoveFile(string oldPath, string newPath)- {- var physicalOldPath = GetPhysicalPath(oldPath);-- if (!File.Exists(physicalOldPath))- {- throw new Exception($"Cannot move file '{oldPath}' because it does not exist.");- }-- var physicalNewPath = GetPhysicalPath(newPath);-- if (File.Exists(physicalNewPath) || Directory.Exists(physicalNewPath))- {- throw new Exception($"Cannot move file because the new path '{newPath}' already exists.");- }-- File.Move(physicalOldPath, physicalNewPath);-- return Task.CompletedTask;- }-- public async Task CopyFile(string srcPath, string dstPath)- {- var physicalSrcPath = GetPhysicalPath(srcPath);-- if (!File.Exists(physicalSrcPath))- {- throw new Exception($"The file '{srcPath}' does not exist.");- }- var file = await GetFileInfo(srcPath);- var physicalDstPath = GetPhysicalPath(Path.Combine(dstPath));-- if (File.Exists(physicalDstPath) || Directory.Exists(physicalDstPath))- {- throw new Exception($"Cannot copy file because the destination path '{dstPath}' already exists.");- }-- File.Copy(physicalSrcPath, physicalDstPath);- }- public async Task RenameFile(string file, string newName)- {- var physicalSrcFile = GetPhysicalPath(file);-- if (!File.Exists(physicalSrcFile))- {- throw new Exception($"The file '{file}' does not exist.");- }-- var physicalFile = await GetFileInfo(file);-- var newphysicalFile = GetPhysicalPath(Path.Combine(physicalFile.DirectoryPath, newName));- if (File.Exists(newphysicalFile))- {- throw new Exception($"The file '{newName}' does exist.");- }- File.Move(physicalSrcFile, newphysicalFile);-- }- public Task<Stream> GetFileStream(string path)- {- var physicalPath = GetPhysicalPath(path);-- if (!File.Exists(physicalPath))- {- throw new Exception($"Cannot get file stream because the file '{path}' does not exist.");- }-- var stream = File.OpenRead(physicalPath);+ public async Task RenameFile(string file, string newName)+ {+ var physicalSrcFile = GetPhysicalPath(file);- return Task.FromResult<Stream>(stream);- }+ if (!File.Exists(physicalSrcFile)) throw new Exception($"The file '{file}' does not exist.");++ var physicalFile = await GetFileInfo(file);++ var newphysicalFile = GetPhysicalPath(Path.Combine(physicalFile.DirectoryPath, newName));+ if (File.Exists(newphysicalFile)) throw new Exception($"The file '{newName}' does exist.");+ File.Move(physicalSrcFile, newphysicalFile);+ }++ public Task<Stream> GetFileStream(string path)+ {+ var physicalPath = GetPhysicalPath(path);++ if (!File.Exists(physicalPath))+ throw new Exception($"Cannot get file stream because the file '{path}' does not exist.");++ var stream = File.OpenRead(physicalPath);++ return Task.FromResult<Stream>(stream);+ }++ public Task<Stream> GetFileStream(IFileStoreEntry fileStoreEntry)+ {+ var physicalPath = GetPhysicalPath(fileStoreEntry.Path);+ if (!File.Exists(physicalPath))+ throw new Exception($"Cannot get file stream because the file '{fileStoreEntry.Path}' does not exist.");++ var stream = File.OpenRead(physicalPath);++ return Task.FromResult<Stream>(stream);+ }++ public async Task<string> CreateFileFromStream(string path, Stream inputStream, bool overwrite = false)+ {+ var physicalPath = GetPhysicalPath(path);++ if (!overwrite && File.Exists(physicalPath))+ throw new Exception($"Cannot create file '{path}' because it already exists.");++ if (Directory.Exists(physicalPath))+ throw new Exception($"Cannot create file '{path}' because it already exists as a directory.");++ // Create directory path if it doesn't exist.+ var physicalDirectoryPath = Path.GetDirectoryName(physicalPath);+ Directory.CreateDirectory(physicalDirectoryPath);++ var fileInfo = new FileInfo(physicalPath);+ await using var outputStream = fileInfo.Create();+ await inputStream.CopyToAsync(outputStream);++ return path;+ }++ public Task<string> ReadAllText(string path)+ {+ var physicalPath = GetPhysicalPath(path);++ if (!File.Exists(physicalPath)) throw new Exception("File not exists.");+ return File.ReadAllTextAsync(physicalPath);+ }++ public Task WriteAllText(string path, string text)+ {+ var physicalPath = GetPhysicalPath(path);++ if (!File.Exists(physicalPath))+ File.Create(physicalPath).Close();++ return File.WriteAllTextAsync(physicalPath, text, Encoding.UTF8);+ }+++ /// <summary>+ /// Translates a relative path in the virtual file store to a physical path in the underlying file system.+ /// </summary>+ /// <param name="path">The relative path within the file store.</param>+ /// <returns></returns>+ /// <remarks>The resulting physical path is verified to be inside designated root file system path.</remarks>+ private string GetPhysicalPath(string path)+ {+ path = this.NormalizePath(path);- public Task<Stream> GetFileStream(IFileStoreEntry fileStoreEntry)- {- var physicalPath = GetPhysicalPath(fileStoreEntry.Path);- if (!File.Exists(physicalPath))- {- throw new Exception($"Cannot get file stream because the file '{fileStoreEntry.Path}' does not exist.");- }+ var physicalPath = string.IsNullOrEmpty(path) ? _fileSystemPath : Path.Combine(_fileSystemPath, path);- var stream = File.OpenRead(physicalPath);-- return Task.FromResult<Stream>(stream);- }-- public async Task<string> CreateFileFromStream(string path, Stream inputStream, bool overwrite = false)- {- var physicalPath = GetPhysicalPath(path);-- if (!overwrite && File.Exists(physicalPath))- {- throw new Exception($"Cannot create file '{path}' because it already exists.");- }-- if (Directory.Exists(physicalPath))- {- throw new Exception($"Cannot create file '{path}' because it already exists as a directory.");- }-- // Create directory path if it doesn't exist.- var physicalDirectoryPath = Path.GetDirectoryName(physicalPath);- Directory.CreateDirectory(physicalDirectoryPath);-- var fileInfo = new FileInfo(physicalPath);- await using var outputStream = fileInfo.Create();- await inputStream.CopyToAsync(outputStream);-- return path;- }-- public Task<string> ReadAllText(string path)- {- var physicalPath = GetPhysicalPath(path);-- if (!File.Exists(physicalPath))- {- throw new Exception("File not exists.");- }- return File.ReadAllTextAsync(physicalPath);- }-- public Task WriteAllText(string path, string text)- {- var physicalPath = GetPhysicalPath(path);-- if (!File.Exists(physicalPath))- File.Create(physicalPath).Close();-- return File.WriteAllTextAsync(physicalPath, text, Encoding.UTF8);- }--- /// <summary>- /// Translates a relative path in the virtual file store to a physical path in the underlying file system.- /// </summary>- /// <param name="path">The relative path within the file store.</param>- /// <returns></returns>- /// <remarks>The resulting physical path is verified to be inside designated root file system path.</remarks>- private string GetPhysicalPath(string path)- {- path = this.NormalizePath(path);-- var physicalPath = string.IsNullOrEmpty(path) ? _fileSystemPath : Path.Combine(_fileSystemPath, path);-- // Verify that the resulting path is inside the root file system path.- var pathIsAllowed = Path.GetFullPath(physicalPath).StartsWith(_fileSystemPath, StringComparison.OrdinalIgnoreCase);- if (!pathIsAllowed)- {- throw new Exception($"The path '{path}' resolves to a physical path outside the file system store root.");- }-- return physicalPath;- }+ // Verify that the resulting path is inside the root file system path.+ var pathIsAllowed = Path.GetFullPath(physicalPath)+ .StartsWith(_fileSystemPath, StringComparison.OrdinalIgnoreCase);+ if (!pathIsAllowed)+ throw new Exception($"The path '{path}' resolves to a physical path outside the file system store root.");+ return physicalPath;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Storage/Services/FileSystemStoreEntry.cs b/src/Business/Grand.Business.Storage/Services/FileSystemStoreEntry.csindex 869bb7b41..0b4b04ab6 100644--- a/src/Business/Grand.Business.Storage/Services/FileSystemStoreEntry.cs+++ b/src/Business/Grand.Business.Storage/Services/FileSystemStoreEntry.cs@@ -1,26 +1,26 @@//Source https://github.com/OrchardCMS/OrchardCore/tree/dev/src/OrchardCore+using Grand.Business.Core.Interfaces.Storage;using Microsoft.Extensions.FileProviders;-namespace Grand.Business.Storage.Services+namespace Grand.Business.Storage.Services;++public class FileSystemStoreEntry : IFileStoreEntry{- public class FileSystemStoreEntry : IFileStoreEntry+ private readonly IFileInfo _fileInfo;++ internal FileSystemStoreEntry(string path, IFileInfo fileInfo){- private readonly IFileInfo _fileInfo;- private readonly string _path;+ _fileInfo = fileInfo ?? throw new ArgumentNullException(nameof(fileInfo));+ Path = path ?? throw new ArgumentNullException(nameof(path));+ }- internal FileSystemStoreEntry(string path, IFileInfo fileInfo)- {- _fileInfo = fileInfo ?? throw new ArgumentNullException(nameof(fileInfo));- _path = path ?? throw new ArgumentNullException(nameof(path));- }+ public string Path { get; }- public string Path => _path;- public string Name => _fileInfo.Name;- public string DirectoryPath => _path[..^Name.Length].TrimEnd('/');- public string PhysicalPath => _fileInfo.PhysicalPath;- public DateTime LastModifiedUtc => _fileInfo.LastModified.UtcDateTime;- public long Length => _fileInfo.Length;- public bool IsDirectory => _fileInfo.IsDirectory;- }-}+ public string Name => _fileInfo.Name;+ public string DirectoryPath => Path[..^Name.Length].TrimEnd('/');+ public string PhysicalPath => _fileInfo.PhysicalPath;+ public DateTime LastModifiedUtc => _fileInfo.LastModified.UtcDateTime;+ public long Length => _fileInfo.Length;+ public bool IsDirectory => _fileInfo.IsDirectory;+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Storage/Services/PictureService.cs b/src/Business/Grand.Business.Storage/Services/PictureService.csindex f28cda44b..7cfc1d732 100644--- a/src/Business/Grand.Business.Storage/Services/PictureService.cs+++ b/src/Business/Grand.Business.Storage/Services/PictureService.cs@@ -1,8 +1,8 @@using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Storage;+using Grand.Data;using Grand.Domain;using Grand.Domain.Common;-using Grand.Data;using Grand.Domain.Media;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;@@ -13,861 +13,854 @@ using Microsoft.Extensions.Logging;using SkiaSharp;using System.Linq.Expressions;-namespace Grand.Business.Storage.Services+namespace Grand.Business.Storage.Services;++/// <summary>+/// Picture service+/// </summary>+public class PictureService : IPictureService{+ #region Ctor+/// <summary>- /// Picture service+ /// Ctor/// </summary>- public class PictureService : IPictureService+ /// <param name="pictureRepository">Picture repository</param>+ /// <param name="logger">Logger</param>+ /// <param name="mediator">Mediator</param>+ /// <param name="cacheBase">Cache manager</param>+ /// <param name="mediaFileStore">Media file storage</param>+ /// <param name="mediaSettings">Media settings</param>+ /// <param name="storageSettings">Storage settings</param>+ public PictureService(IRepository<Picture> pictureRepository,+ ILogger<PictureService> logger,+ IMediator mediator,+ ICacheBase cacheBase,+ IMediaFileStore mediaFileStore,+ MediaSettings mediaSettings,+ StorageSettings storageSettings){+ _pictureRepository = pictureRepository;+ _logger = logger;+ _mediator = mediator;+ _cacheBase = cacheBase;+ _mediaFileStore = mediaFileStore;+ _mediaSettings = mediaSettings;+ _storageSettings = storageSettings;+ }- #region Fields-- private readonly IRepository<Picture> _pictureRepository;- private readonly ILogger<PictureService> _logger;- private readonly IMediator _mediator;- private readonly ICacheBase _cacheBase;- private readonly IMediaFileStore _mediaFileStore;- private readonly MediaSettings _mediaSettings;- private readonly StorageSettings _storageSettings;-- #endregion-- #region Ctor-- /// <summary>- /// Ctor- /// </summary>- /// <param name="pictureRepository">Picture repository</param>- /// <param name="logger">Logger</param>- /// <param name="mediator">Mediator</param>- /// <param name="cacheBase">Cache manager</param>- /// <param name="mediaFileStore">Media file storage</param>- /// <param name="mediaSettings">Media settings</param>- /// <param name="storageSettings">Storage settings</param>- public PictureService(IRepository<Picture> pictureRepository,- ILogger<PictureService> logger,- IMediator mediator,- ICacheBase cacheBase,- IMediaFileStore mediaFileStore,- MediaSettings mediaSettings,- StorageSettings storageSettings)- {- _pictureRepository = pictureRepository;- _logger = logger;- _mediator = mediator;- _cacheBase = cacheBase;- _mediaFileStore = mediaFileStore;- _mediaSettings = mediaSettings;- _storageSettings = storageSettings;- }-- #endregion-- #region Utilities-- /// <summary>- /// Returns the file extension from mime type.- /// </summary>- /// <param name="mimeType">Mime type</param>- /// <returns>File extension</returns>- private string GetFileExtensionFromMimeType(string mimeType)- {- if (mimeType == null)- return null;-- var parts = mimeType.Split('/');- var lastPart = parts[^1];- switch (lastPart)- {- case "pjpeg":- lastPart = "jpg";- break;- case "x-png":- lastPart = "png";- break;- case "x-icon":- lastPart = "ico";- break;- }- return lastPart;- }+ #endregion- /// <summary>- /// Loads a picture from file- /// </summary>- /// <param name="pictureId">Picture identifier</param>- /// <param name="mimeType">MIME type</param>- /// <returns>Picture binary</returns>- protected async Task<byte[]> LoadPictureFromFile(string pictureId, string mimeType)- {- var lastPart = GetFileExtensionFromMimeType(mimeType);- var fileName = $"{pictureId}_0.{lastPart}";- var filePath = await GetPicturePhysicalPath(fileName);- if (string.IsNullOrEmpty(filePath))- return Array.Empty<byte>();+ #region Fields- return await File.ReadAllBytesAsync(filePath);- }+ private readonly IRepository<Picture> _pictureRepository;+ private readonly ILogger<PictureService> _logger;+ private readonly IMediator _mediator;+ private readonly ICacheBase _cacheBase;+ private readonly IMediaFileStore _mediaFileStore;+ private readonly MediaSettings _mediaSettings;+ private readonly StorageSettings _storageSettings;+ #endregion- /// <summary>- /// Delete picture thumbs- /// </summary>- /// <param name="picture">Picture</param>- protected virtual Task DeletePictureThumbs(Picture picture)- {- var filter = $"{picture.Id}*.*";- var thumbDirectoryPath = _mediaFileStore.GetDirectoryInfo(CommonPath.ImageThumbPath);- if (thumbDirectoryPath == null) return Task.CompletedTask;- var currentFiles = Directory.GetFiles(thumbDirectoryPath.PhysicalPath, filter, SearchOption.AllDirectories);- foreach (var currentFileName in currentFiles)- {- try- {- if (File.Exists(currentFileName))- File.Delete(currentFileName);- }- catch (Exception ex)- {- _logger.LogError(ex, ex.Message);- }- }- return Task.CompletedTask;- }+ #region Utilities- /// <summary>- /// Get picture (thumb) physical path- /// </summary>- /// <param name="thumbFileName">Filename</param>- /// <returns>Local picture physical path</returns>- protected virtual async Task<string> GetThumbPhysicalPath(string thumbFileName)- {- var thumbFile = _mediaFileStore.Combine(CommonPath.ImageThumbPath, thumbFileName);- var fileInfo = await _mediaFileStore.GetFileInfo(thumbFile);- return fileInfo?.PhysicalPath;- }+ /// <summary>+ /// Returns the file extension from mime type.+ /// </summary>+ /// <param name="mimeType">Mime type</param>+ /// <returns>File extension</returns>+ private string GetFileExtensionFromMimeType(string mimeType)+ {+ if (mimeType == null)+ return null;- /// <summary>- /// Get picture (thumb) URL- /// </summary>- /// <param name="thumbFileName">Filename</param>- /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>- /// <returns>Local picture thumb path</returns>- protected virtual string GetThumbUrl(string thumbFileName, string storeLocation = null)+ var parts = mimeType.Split('/');+ var lastPart = parts[^1];+ switch (lastPart){- storeLocation = !string.IsNullOrEmpty(storeLocation) ? storeLocation : "";- return _mediaFileStore.Combine(storeLocation, CommonPath.Param, CommonPath.ImageThumbPath, thumbFileName);+ case "pjpeg":+ lastPart = "jpg";+ break;+ case "x-png":+ lastPart = "png";+ break;+ case "x-icon":+ lastPart = "ico";+ break;}- /// <summary>- /// Get picture physical path. Used when images stored on file system (not in the database)- /// </summary>- /// <param name="fileName">Filename</param>- /// <returns>Physical picture path</returns>- protected virtual async Task<string> GetPicturePhysicalPath(string fileName)- {- var fileInfo = await _mediaFileStore.GetFileInfo(_mediaFileStore.Combine(CommonPath.ImagePath, fileName));- return fileInfo?.PhysicalPath;- }+ return lastPart;+ }- /// <summary>- /// Gets the loaded picture binary depending on picture storage settings- /// </summary>- /// <param name="picture">Picture</param>- /// <param name="fromDb">Load from database; otherwise, from file system</param>- /// <returns>Picture binary</returns>- public virtual async Task<byte[]> LoadPictureBinary(Picture picture, bool fromDb)- {- ArgumentNullException.ThrowIfNull(picture);+ /// <summary>+ /// Loads a picture from file+ /// </summary>+ /// <param name="pictureId">Picture identifier</param>+ /// <param name="mimeType">MIME type</param>+ /// <returns>Picture binary</returns>+ protected async Task<byte[]> LoadPictureFromFile(string pictureId, string mimeType)+ {+ var lastPart = GetFileExtensionFromMimeType(mimeType);+ var fileName = $"{pictureId}_0.{lastPart}";+ var filePath = await GetPicturePhysicalPath(fileName);+ if (string.IsNullOrEmpty(filePath))+ return Array.Empty<byte>();- var result = fromDb- ? (await _pictureRepository.GetByIdAsync(picture.Id)).PictureBinary- : await LoadPictureFromFile(picture.Id, picture.MimeType);+ return await File.ReadAllBytesAsync(filePath);+ }- return result;- }- /// <summary>- /// Save a value indicating whether some file (thumb) already exists- /// </summary>- /// <param name="thumbFileName">Thumb file name</param>- /// <param name="binary">Picture binary</param>- protected virtual Task SaveThumb(string thumbFileName, byte[] binary)- {+ /// <summary>+ /// Delete picture thumbs+ /// </summary>+ /// <param name="picture">Picture</param>+ protected virtual Task DeletePictureThumbs(Picture picture)+ {+ var filter = $"{picture.Id}*.*";+ var thumbDirectoryPath = _mediaFileStore.GetDirectoryInfo(CommonPath.ImageThumbPath);+ if (thumbDirectoryPath == null) return Task.CompletedTask;+ var currentFiles = Directory.GetFiles(thumbDirectoryPath.PhysicalPath, filter, SearchOption.AllDirectories);+ foreach (var currentFileName in currentFiles)try{- var dirThumb = _mediaFileStore.GetDirectoryInfo(CommonPath.ImageThumbPath);- if (dirThumb == null)- {- var result = _mediaFileStore.TryCreateDirectory(CommonPath.ImageThumbPath);- if (result)- dirThumb = _mediaFileStore.GetDirectoryInfo(CommonPath.ImageThumbPath);- }-- if (dirThumb != null)- {- var file = _mediaFileStore.Combine(dirThumb.PhysicalPath, thumbFileName);- File.WriteAllBytes(file, binary ?? Array.Empty<byte>());- }- else- _logger.LogError("Directory thumb not exist");-+ if (File.Exists(currentFileName))+ File.Delete(currentFileName);}catch (Exception ex){_logger.LogError(ex, ex.Message);}- return Task.CompletedTask;- }+ return Task.CompletedTask;+ }++ /// <summary>+ /// Get picture (thumb) physical path+ /// </summary>+ /// <param name="thumbFileName">Filename</param>+ /// <returns>Local picture physical path</returns>+ protected virtual async Task<string> GetThumbPhysicalPath(string thumbFileName)+ {+ var thumbFile = _mediaFileStore.Combine(CommonPath.ImageThumbPath, thumbFileName);+ var fileInfo = await _mediaFileStore.GetFileInfo(thumbFile);+ return fileInfo?.PhysicalPath;+ }++ /// <summary>+ /// Get picture (thumb) URL+ /// </summary>+ /// <param name="thumbFileName">Filename</param>+ /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>+ /// <returns>Local picture thumb path</returns>+ protected virtual string GetThumbUrl(string thumbFileName, string storeLocation = null)+ {+ storeLocation = !string.IsNullOrEmpty(storeLocation) ? storeLocation : "";+ return _mediaFileStore.Combine(storeLocation, CommonPath.Param, CommonPath.ImageThumbPath, thumbFileName);+ }- #endregion+ /// <summary>+ /// Get picture physical path. Used when images stored on file system (not in the database)+ /// </summary>+ /// <param name="fileName">Filename</param>+ /// <returns>Physical picture path</returns>+ protected virtual async Task<string> GetPicturePhysicalPath(string fileName)+ {+ var fileInfo = await _mediaFileStore.GetFileInfo(_mediaFileStore.Combine(CommonPath.ImagePath, fileName));+ return fileInfo?.PhysicalPath;+ }- #region Getting picture local path/URL methods+ /// <summary>+ /// Gets the loaded picture binary depending on picture storage settings+ /// </summary>+ /// <param name="picture">Picture</param>+ /// <param name="fromDb">Load from database; otherwise, from file system</param>+ /// <returns>Picture binary</returns>+ public virtual async Task<byte[]> LoadPictureBinary(Picture picture, bool fromDb)+ {+ ArgumentNullException.ThrowIfNull(picture);- /// <summary>- /// Gets the loaded picture binary depending on picture storage settings- /// </summary>- /// <param name="picture">Picture</param>- /// <returns>Picture binary</returns>- public virtual async Task<byte[]> LoadPictureBinary(Picture picture)- {- return await LoadPictureBinary(picture, _storageSettings.PictureStoreInDb);- }+ var result = fromDb+ ? (await _pictureRepository.GetByIdAsync(picture.Id)).PictureBinary+ : await LoadPictureFromFile(picture.Id, picture.MimeType);- /// <summary>- /// Get picture SEO friendly name- /// </summary>- /// <param name="name">Name</param>- /// <returns>Result</returns>- public virtual string GetPictureSeName(string name)- {- return SeoExtensions.GenerateSlug(name, true, false, false);- }+ return result;+ }- /// <summary>- /// Gets the default picture URL- /// </summary>- /// <param name="targetSize">The target picture size (longest side)</param>- /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>- /// <returns>Picture URL</returns>- public virtual async Task<string> GetDefaultPictureUrl(int targetSize = 0, string storeLocation = null)+ /// <summary>+ /// Save a value indicating whether some file (thumb) already exists+ /// </summary>+ /// <param name="thumbFileName">Thumb file name</param>+ /// <param name="binary">Picture binary</param>+ protected virtual Task SaveThumb(string thumbFileName, byte[] binary)+ {+ try{- var filePath = await GetPicturePhysicalPath(_mediaSettings.DefaultImageName);- if (string.IsNullOrEmpty(filePath))+ var dirThumb = _mediaFileStore.GetDirectoryInfo(CommonPath.ImageThumbPath);+ if (dirThumb == null){- return _mediaFileStore.Combine(CommonPath.ImagePath, "no-image.png");+ var result = _mediaFileStore.TryCreateDirectory(CommonPath.ImageThumbPath);+ if (result)+ dirThumb = _mediaFileStore.GetDirectoryInfo(CommonPath.ImageThumbPath);}- if (targetSize == 0)++ if (dirThumb != null){- return !string.IsNullOrEmpty(storeLocation)- ? storeLocation : _mediaFileStore.Combine(CommonPath.ImagePath, _mediaSettings.DefaultImageName);+ var file = _mediaFileStore.Combine(dirThumb.PhysicalPath, thumbFileName);+ File.WriteAllBytes(file, binary ?? Array.Empty<byte>());}-- var fileExtension = Path.GetExtension(filePath);- var thumbFileName = $"{Path.GetFileNameWithoutExtension(filePath)}_{targetSize}{fileExtension}";-- var thumbFilePath = await GetThumbPhysicalPath(thumbFileName);-- if (!string.IsNullOrEmpty(thumbFilePath))- return GetThumbUrl(thumbFileName, storeLocation);-- using (var mutex = new Mutex(false, thumbFileName))+ else{- mutex.WaitOne();- using (var image = SKBitmap.Decode(filePath))- {- var pictureBinary = ApplyResize(image, EncodedImageFormat(fileExtension), targetSize);- if (pictureBinary != null)- await SaveThumb(thumbFileName, pictureBinary);- }- mutex.ReleaseMutex();+ _logger.LogError("Directory thumb not exist");}- var url = GetThumbUrl(thumbFileName, storeLocation);- return url;}-- /// <summary>- /// Get a picture URL- /// </summary>- /// <param name="pictureId">Picture identifier</param>- /// <param name="targetSize">The target picture size (longest side)</param>- /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>- /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>- /// <returns>Picture URL</returns>- public virtual async Task<string> GetPictureUrl(string pictureId,- int targetSize = 0,- bool showDefaultPicture = true,- string storeLocation = null)+ catch (Exception ex){- var pictureKey = string.Format(CacheKey.PICTURE_BY_KEY, pictureId, targetSize, showDefaultPicture, storeLocation);- return await _cacheBase.GetAsync(pictureKey, async () =>- {- var picture = await GetPictureById(pictureId);- return await GetPictureUrl(picture, targetSize, showDefaultPicture, storeLocation);- });+ _logger.LogError(ex, ex.Message);}- /// <summary>- /// Get a picture URL- /// </summary>- /// <param name="picture">Picture instance</param>- /// <param name="targetSize">The target picture size (longest side)</param>- /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>- /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>- /// <returns>Picture URL</returns>- public virtual async Task<string> GetPictureUrl(Picture picture,- int targetSize = 0,- bool showDefaultPicture = true,- string storeLocation = null)- {- if (picture == null)- return showDefaultPicture ? await GetDefaultPictureUrl(targetSize, storeLocation) : string.Empty;-- if (picture.IsNew)- {- await DeletePictureThumbs(picture);-- picture.IsNew = false;- await _pictureRepository.UpdateField(picture.Id, x => x.IsNew, picture.IsNew);- }-- var seoFileName = picture.SeoFilename;- var lastPart = GetFileExtensionFromMimeType(picture.MimeType);- string thumbFileName;-- if (targetSize == 0)- {- thumbFileName = !string.IsNullOrEmpty(seoFileName) ? $"{picture.Id}_{seoFileName}.{lastPart}"- : $"{picture.Id}.{lastPart}";-- var thumbFilePath = await GetThumbPhysicalPath(thumbFileName);+ return Task.CompletedTask;+ }- if (!string.IsNullOrEmpty(thumbFilePath))- return GetThumbUrl(thumbFileName, storeLocation);+ #endregion- var pictureBinary = await LoadPictureBinary(picture);+ #region Getting picture local path/URL methods- using var mutex = new Mutex(false, thumbFileName);- mutex.WaitOne();- await SaveThumb(thumbFileName, pictureBinary);- mutex.ReleaseMutex();- }- else- {- thumbFileName = !string.IsNullOrEmpty(seoFileName) ? $"{picture.Id}_{seoFileName}_{targetSize}.{lastPart}"- : $"{picture.Id}_{targetSize}.{lastPart}";+ /// <summary>+ /// Gets the loaded picture binary depending on picture storage settings+ /// </summary>+ /// <param name="picture">Picture</param>+ /// <returns>Picture binary</returns>+ public virtual async Task<byte[]> LoadPictureBinary(Picture picture)+ {+ return await LoadPictureBinary(picture, _storageSettings.PictureStoreInDb);+ }- var thumbFilePath = await GetThumbPhysicalPath(thumbFileName);+ /// <summary>+ /// Get picture SEO friendly name+ /// </summary>+ /// <param name="name">Name</param>+ /// <returns>Result</returns>+ public virtual string GetPictureSeName(string name)+ {+ return SeoExtensions.GenerateSlug(name, true, false, false);+ }- if (!string.IsNullOrEmpty(thumbFilePath))- return GetThumbUrl(thumbFileName, storeLocation);+ /// <summary>+ /// Gets the default picture URL+ /// </summary>+ /// <param name="targetSize">The target picture size (longest side)</param>+ /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>+ /// <returns>Picture URL</returns>+ public virtual async Task<string> GetDefaultPictureUrl(int targetSize = 0, string storeLocation = null)+ {+ var filePath = await GetPicturePhysicalPath(_mediaSettings.DefaultImageName);+ if (string.IsNullOrEmpty(filePath)) return _mediaFileStore.Combine(CommonPath.ImagePath, "no-image.png");+ if (targetSize == 0)+ return !string.IsNullOrEmpty(storeLocation)+ ? storeLocation+ : _mediaFileStore.Combine(CommonPath.ImagePath, _mediaSettings.DefaultImageName);- var pictureBinary = await LoadPictureBinary(picture);+ var fileExtension = Path.GetExtension(filePath);+ var thumbFileName = $"{Path.GetFileNameWithoutExtension(filePath)}_{targetSize}{fileExtension}";- using var mutex = new Mutex(false, thumbFileName);- mutex.WaitOne();- if (pictureBinary != null)- {- try- {- using var image = SKBitmap.Decode(pictureBinary);- var resizedBinary = ApplyResize(image, EncodedImageFormat(picture.MimeType), targetSize);- if (resizedBinary != null)- pictureBinary = resizedBinary;- }- catch- {- // ignored- }- }- await SaveThumb(thumbFileName, pictureBinary);+ var thumbFilePath = await GetThumbPhysicalPath(thumbFileName);- mutex.ReleaseMutex();- }+ if (!string.IsNullOrEmpty(thumbFilePath))return GetThumbUrl(thumbFileName, storeLocation);- }- /// <summary>- /// Get a picture physical path- /// </summary>- /// <param name="picture">Picture instance</param>- /// <param name="targetSize">The target picture size (longest side)</param>- /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>- /// <returns></returns>- public virtual async Task<string> GetThumbPhysicalPath(Picture picture, int targetSize = 0, bool showDefaultPicture = true)+ using (var mutex = new Mutex(false, thumbFileName)){- var url = await GetPictureUrl(picture, targetSize, showDefaultPicture);- if (string.IsNullOrEmpty(url))- return string.Empty;+ mutex.WaitOne();+ using (var image = SKBitmap.Decode(filePath))+ {+ var pictureBinary = ApplyResize(image, EncodedImageFormat(fileExtension), targetSize);+ if (pictureBinary != null)+ await SaveThumb(thumbFileName, pictureBinary);+ }- return await GetThumbPhysicalPath(Path.GetFileName(url));+ mutex.ReleaseMutex();}- #endregion+ var url = GetThumbUrl(thumbFileName, storeLocation);+ return url;+ }++ /// <summary>+ /// Get a picture URL+ /// </summary>+ /// <param name="pictureId">Picture identifier</param>+ /// <param name="targetSize">The target picture size (longest side)</param>+ /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>+ /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>+ /// <returns>Picture URL</returns>+ public virtual async Task<string> GetPictureUrl(string pictureId,+ int targetSize = 0,+ bool showDefaultPicture = true,+ string storeLocation = null)+ {+ var pictureKey = string.Format(CacheKey.PICTURE_BY_KEY, pictureId, targetSize, showDefaultPicture,+ storeLocation);+ return await _cacheBase.GetAsync(pictureKey, async () =>+ {+ var picture = await GetPictureById(pictureId);+ return await GetPictureUrl(picture, targetSize, showDefaultPicture, storeLocation);+ });+ }- #region CRUD methods+ /// <summary>+ /// Get a picture URL+ /// </summary>+ /// <param name="picture">Picture instance</param>+ /// <param name="targetSize">The target picture size (longest side)</param>+ /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>+ /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>+ /// <returns>Picture URL</returns>+ public virtual async Task<string> GetPictureUrl(Picture picture,+ int targetSize = 0,+ bool showDefaultPicture = true,+ string storeLocation = null)+ {+ if (picture == null)+ return showDefaultPicture ? await GetDefaultPictureUrl(targetSize, storeLocation) : string.Empty;- /// <summary>- /// Gets a picture- /// </summary>- /// <param name="pictureId">Picture identifier</param>- /// <returns>Picture</returns>- public virtual async Task<Picture> GetPictureById(string pictureId)+ if (picture.IsNew){- var pictureKey = string.Format(CacheKey.PICTURE_BY_ID, pictureId);- return await _cacheBase.GetAsync(pictureKey, async () =>- {- var query = _pictureRepository.Table- .Where(p => p.Id == pictureId)- .Select(p =>- new Picture {- Id = p.Id,- AltAttribute = p.AltAttribute,- IsNew = p.IsNew,- MimeType = p.MimeType,- SeoFilename = p.SeoFilename,- TitleAttribute = p.TitleAttribute,- Reference = p.Reference,- ObjectId = p.ObjectId,- Locales = p.Locales,- Style = p.Style,- ExtraField = p.ExtraField- });- return await Task.FromResult(query.FirstOrDefault());- });+ await DeletePictureThumbs(picture);++ picture.IsNew = false;+ await _pictureRepository.UpdateField(picture.Id, x => x.IsNew, picture.IsNew);}- /// <summary>- /// Deletes a picture- /// </summary>- /// <param name="picture">Picture</param>- public virtual async Task DeletePicture(Picture picture)+ var seoFileName = picture.SeoFilename;+ var lastPart = GetFileExtensionFromMimeType(picture.MimeType);+ string thumbFileName;++ if (targetSize == 0){- ArgumentNullException.ThrowIfNull(picture);+ thumbFileName = !string.IsNullOrEmpty(seoFileName)+ ? $"{picture.Id}_{seoFileName}.{lastPart}"+ : $"{picture.Id}.{lastPart}";- //delete thumbs- await DeletePictureThumbs(picture);+ var thumbFilePath = await GetThumbPhysicalPath(thumbFileName);- //delete from file system- if (!_storageSettings.PictureStoreInDb)- await DeletePictureOnFileSystem(picture);+ if (!string.IsNullOrEmpty(thumbFilePath))+ return GetThumbUrl(thumbFileName, storeLocation);- //delete from database- await _pictureRepository.DeleteAsync(picture);+ var pictureBinary = await LoadPictureBinary(picture);- //event notification- await _mediator.EntityDeleted(picture);+ using var mutex = new Mutex(false, thumbFileName);+ mutex.WaitOne();+ await SaveThumb(thumbFileName, pictureBinary);+ mutex.ReleaseMutex();}-- /// <summary>- /// Delete a picture on file system- /// </summary>- /// <param name="picture">Picture</param>- public virtual async Task DeletePictureOnFileSystem(Picture picture)+ else{- ArgumentNullException.ThrowIfNull(picture);+ thumbFileName = !string.IsNullOrEmpty(seoFileName)+ ? $"{picture.Id}_{seoFileName}_{targetSize}.{lastPart}"+ : $"{picture.Id}_{targetSize}.{lastPart}";- var lastPart = GetFileExtensionFromMimeType(picture.MimeType);- var fileName = $"{picture.Id}_0.{lastPart}";- var filePath = await GetPicturePhysicalPath(fileName);- if (!string.IsNullOrEmpty(filePath))- {- File.Delete(filePath);- }- }+ var thumbFilePath = await GetThumbPhysicalPath(thumbFileName);- public virtual async Task ClearThumbs()- {- const string searchPattern = "*.*";- var path = _mediaFileStore.GetDirectoryInfo(CommonPath.ImageThumbPath)?.PhysicalPath;+ if (!string.IsNullOrEmpty(thumbFilePath))+ return GetThumbUrl(thumbFileName, storeLocation);- if (!Directory.Exists(path))- return;+ var pictureBinary = await LoadPictureBinary(picture);- foreach (var file in Directory.GetFiles(path, searchPattern, SearchOption.AllDirectories))- {- if (file.Contains("placeholder.txt"))- continue;+ using var mutex = new Mutex(false, thumbFileName);+ mutex.WaitOne();+ if (pictureBinary != null)try{- File.Delete(file);+ using var image = SKBitmap.Decode(pictureBinary);+ var resizedBinary = ApplyResize(image, EncodedImageFormat(picture.MimeType), targetSize);+ if (resizedBinary != null)+ pictureBinary = resizedBinary;}- catch (Exception ex)+ catch{- _logger.LogError(ex, ex.Message);+ // ignored}- }- await Task.CompletedTask;- }- /// <summary>- /// Gets a collection of pictures- /// </summary>- /// <param name="pageIndex">Current page</param>- /// <param name="pageSize">Items on each page</param>- /// <returns>Paged list of pictures</returns>- public virtual IPagedList<Picture> GetPictures(int pageIndex = 0, int pageSize = int.MaxValue)- {- var query = from p in _pictureRepository.Table- select p;- var pictures = new PagedList<Picture>(query, pageIndex, pageSize);- return pictures;+ await SaveThumb(thumbFileName, pictureBinary);++ mutex.ReleaseMutex();}- /// <summary>- /// Inserts a picture- /// </summary>- /// <param name="pictureBinary">The picture binary</param>- /// <param name="mimeType">The picture MIME type</param>- /// <param name="seoFilename">The SEO filename</param>- /// <param name="altAttribute">"alt" attribute for "img" HTML element</param>- /// <param name="titleAttribute">"title" attribute for "img" HTML element</param>- /// <param name="isNew">A value indicating whether the picture is new</param>- /// <param name="reference">Reference type</param>- /// <param name="objectId">Object id for reference</param>- /// <param name="validateBinary">A value indicating whether to validated provided picture binary</param>- /// <returns>Picture</returns>- public virtual async Task<Picture> InsertPicture(byte[] pictureBinary, string mimeType, string seoFilename,- string altAttribute = null, string titleAttribute = null,- bool isNew = true, Reference reference = Reference.None, string objectId = "", bool validateBinary = false)- {- mimeType = CommonHelper.EnsureNotNull(mimeType);- mimeType = CommonHelper.EnsureMaximumLength(mimeType, 20);+ return GetThumbUrl(thumbFileName, storeLocation);+ }- seoFilename = CommonHelper.EnsureMaximumLength(seoFilename, 100);+ /// <summary>+ /// Get a picture physical path+ /// </summary>+ /// <param name="picture">Picture instance</param>+ /// <param name="targetSize">The target picture size (longest side)</param>+ /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>+ /// <returns></returns>+ public virtual async Task<string> GetThumbPhysicalPath(Picture picture, int targetSize = 0,+ bool showDefaultPicture = true)+ {+ var url = await GetPictureUrl(picture, targetSize, showDefaultPicture);+ if (string.IsNullOrEmpty(url))+ return string.Empty;++ return await GetThumbPhysicalPath(Path.GetFileName(url));+ }- if (validateBinary)- pictureBinary = ValidatePicture(pictureBinary, mimeType);+ #endregion++ #region CRUD methods++ /// <summary>+ /// Gets a picture+ /// </summary>+ /// <param name="pictureId">Picture identifier</param>+ /// <returns>Picture</returns>+ public virtual async Task<Picture> GetPictureById(string pictureId)+ {+ var pictureKey = string.Format(CacheKey.PICTURE_BY_ID, pictureId);+ return await _cacheBase.GetAsync(pictureKey, async () =>+ {+ var query = _pictureRepository.Table+ .Where(p => p.Id == pictureId)+ .Select(p =>+ new Picture {+ Id = p.Id,+ AltAttribute = p.AltAttribute,+ IsNew = p.IsNew,+ MimeType = p.MimeType,+ SeoFilename = p.SeoFilename,+ TitleAttribute = p.TitleAttribute,+ Reference = p.Reference,+ ObjectId = p.ObjectId,+ Locales = p.Locales,+ Style = p.Style,+ ExtraField = p.ExtraField+ });+ return await Task.FromResult(query.FirstOrDefault());+ });+ }- var picture = new Picture {- PictureBinary = _storageSettings.PictureStoreInDb ? pictureBinary : Array.Empty<byte>(),- MimeType = mimeType,- SeoFilename = seoFilename,- AltAttribute = altAttribute,- TitleAttribute = titleAttribute,- Reference = reference,- ObjectId = objectId,- IsNew = isNew- };- await _pictureRepository.InsertAsync(picture);+ /// <summary>+ /// Deletes a picture+ /// </summary>+ /// <param name="picture">Picture</param>+ public virtual async Task DeletePicture(Picture picture)+ {+ ArgumentNullException.ThrowIfNull(picture);- if (!_storageSettings.PictureStoreInDb)- await SavePictureInFile(picture.Id, pictureBinary, mimeType);+ //delete thumbs+ await DeletePictureThumbs(picture);- //event notification- await _mediator.EntityInserted(picture);+ //delete from file system+ if (!_storageSettings.PictureStoreInDb)+ await DeletePictureOnFileSystem(picture);- return picture;- }+ //delete from database+ await _pictureRepository.DeleteAsync(picture);- /// <summary>- /// Updates the picture- /// </summary>- /// <param name="pictureId">The picture identifier</param>- /// <param name="pictureBinary">The picture binary</param>- /// <param name="mimeType">The picture MIME type</param>- /// <param name="seoFilename">The SEO filename</param>- /// <param name="altAttribute">"alt" attribute for "img" HTML element</param>- /// <param name="titleAttribute">"title" attribute for "img" HTML element</param>- /// <param name="style">style attribute for "img" HTML element</param>- /// <param name="extraField">Extra field</param>- /// <param name="isNew">A value indicating whether the picture is new</param>- /// <param name="validateBinary">A value indicating whether to validated provided picture binary</param>- /// <returns>Picture</returns>- public virtual async Task<Picture> UpdatePicture(string pictureId, byte[] pictureBinary, string mimeType,- string seoFilename, string altAttribute = null, string titleAttribute = null,- string style = null, string extraField = null,- bool isNew = true, bool validateBinary = true)- {- mimeType = CommonHelper.EnsureNotNull(mimeType);- mimeType = CommonHelper.EnsureMaximumLength(mimeType, 20);+ //event notification+ await _mediator.EntityDeleted(picture);+ }- seoFilename = CommonHelper.EnsureMaximumLength(seoFilename, 100);+ /// <summary>+ /// Delete a picture on file system+ /// </summary>+ /// <param name="picture">Picture</param>+ public virtual async Task DeletePictureOnFileSystem(Picture picture)+ {+ ArgumentNullException.ThrowIfNull(picture);- if (validateBinary && pictureBinary != null)- pictureBinary = ValidatePicture(pictureBinary, mimeType);+ var lastPart = GetFileExtensionFromMimeType(picture.MimeType);+ var fileName = $"{picture.Id}_0.{lastPart}";+ var filePath = await GetPicturePhysicalPath(fileName);+ if (!string.IsNullOrEmpty(filePath)) File.Delete(filePath);+ }- var picture = await GetPictureById(pictureId);- if (picture == null)- return null;+ public virtual async Task ClearThumbs()+ {+ const string searchPattern = "*.*";+ var path = _mediaFileStore.GetDirectoryInfo(CommonPath.ImageThumbPath)?.PhysicalPath;- //delete old thumbs if a picture has been changed- if (seoFilename != picture.SeoFilename || pictureBinary != null)- await DeletePictureThumbs(picture);+ if (!Directory.Exists(path))+ return;- if (pictureBinary != null)+ foreach (var file in Directory.GetFiles(path, searchPattern, SearchOption.AllDirectories))+ {+ if (file.Contains("placeholder.txt"))+ continue;+ try+ {+ File.Delete(file);+ }+ catch (Exception ex){- picture.PictureBinary = _storageSettings.PictureStoreInDb ? pictureBinary : Array.Empty<byte>();- await _pictureRepository.UpdateField(picture.Id, x => x.PictureBinary, picture.PictureBinary);+ _logger.LogError(ex, ex.Message);}+ }- picture.MimeType = mimeType;- await _pictureRepository.UpdateField(picture.Id, x => x.MimeType, picture.MimeType);+ await Task.CompletedTask;+ }- picture.SeoFilename = seoFilename;- await _pictureRepository.UpdateField(picture.Id, x => x.SeoFilename, picture.SeoFilename);+ /// <summary>+ /// Gets a collection of pictures+ /// </summary>+ /// <param name="pageIndex">Current page</param>+ /// <param name="pageSize">Items on each page</param>+ /// <returns>Paged list of pictures</returns>+ public virtual IPagedList<Picture> GetPictures(int pageIndex = 0, int pageSize = int.MaxValue)+ {+ var query = from p in _pictureRepository.Table+ select p;+ var pictures = new PagedList<Picture>(query, pageIndex, pageSize);+ return pictures;+ }- picture.AltAttribute = altAttribute;- await _pictureRepository.UpdateField(picture.Id, x => x.AltAttribute, picture.AltAttribute);+ /// <summary>+ /// Inserts a picture+ /// </summary>+ /// <param name="pictureBinary">The picture binary</param>+ /// <param name="mimeType">The picture MIME type</param>+ /// <param name="seoFilename">The SEO filename</param>+ /// <param name="altAttribute">"alt" attribute for "img" HTML element</param>+ /// <param name="titleAttribute">"title" attribute for "img" HTML element</param>+ /// <param name="isNew">A value indicating whether the picture is new</param>+ /// <param name="reference">Reference type</param>+ /// <param name="objectId">Object id for reference</param>+ /// <param name="validateBinary">A value indicating whether to validated provided picture binary</param>+ /// <returns>Picture</returns>+ public virtual async Task<Picture> InsertPicture(byte[] pictureBinary, string mimeType, string seoFilename,+ string altAttribute = null, string titleAttribute = null,+ bool isNew = true, Reference reference = Reference.None, string objectId = "", bool validateBinary = false)+ {+ mimeType = CommonHelper.EnsureNotNull(mimeType);+ mimeType = CommonHelper.EnsureMaximumLength(mimeType, 20);- picture.TitleAttribute = titleAttribute;- await _pictureRepository.UpdateField(picture.Id, x => x.TitleAttribute, picture.TitleAttribute);+ seoFilename = CommonHelper.EnsureMaximumLength(seoFilename, 100);- picture.Style = style;- await _pictureRepository.UpdateField(picture.Id, x => x.Style, picture.Style);+ if (validateBinary)+ pictureBinary = ValidatePicture(pictureBinary, mimeType);- picture.ExtraField = extraField;- await _pictureRepository.UpdateField(picture.Id, x => x.ExtraField, picture.ExtraField);+ var picture = new Picture {+ PictureBinary = _storageSettings.PictureStoreInDb ? pictureBinary : Array.Empty<byte>(),+ MimeType = mimeType,+ SeoFilename = seoFilename,+ AltAttribute = altAttribute,+ TitleAttribute = titleAttribute,+ Reference = reference,+ ObjectId = objectId,+ IsNew = isNew+ };+ await _pictureRepository.InsertAsync(picture);- picture.IsNew = isNew;- await _pictureRepository.UpdateField(picture.Id, x => x.IsNew, picture.IsNew);+ if (!_storageSettings.PictureStoreInDb)+ await SavePictureInFile(picture.Id, pictureBinary, mimeType);- if (!_storageSettings.PictureStoreInDb && pictureBinary != null)- await SavePictureInFile(picture.Id, pictureBinary, mimeType);+ //event notification+ await _mediator.EntityInserted(picture);- //event notification- await _mediator.EntityUpdated(picture);+ return picture;+ }- //clare cache- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PICTURE_BY_ID, picture.Id));+ /// <summary>+ /// Updates the picture+ /// </summary>+ /// <param name="pictureId">The picture identifier</param>+ /// <param name="pictureBinary">The picture binary</param>+ /// <param name="mimeType">The picture MIME type</param>+ /// <param name="seoFilename">The SEO filename</param>+ /// <param name="altAttribute">"alt" attribute for "img" HTML element</param>+ /// <param name="titleAttribute">"title" attribute for "img" HTML element</param>+ /// <param name="style">style attribute for "img" HTML element</param>+ /// <param name="extraField">Extra field</param>+ /// <param name="isNew">A value indicating whether the picture is new</param>+ /// <param name="validateBinary">A value indicating whether to validated provided picture binary</param>+ /// <returns>Picture</returns>+ public virtual async Task<Picture> UpdatePicture(string pictureId, byte[] pictureBinary, string mimeType,+ string seoFilename, string altAttribute = null, string titleAttribute = null,+ string style = null, string extraField = null,+ bool isNew = true, bool validateBinary = true)+ {+ mimeType = CommonHelper.EnsureNotNull(mimeType);+ mimeType = CommonHelper.EnsureMaximumLength(mimeType, 20);- return picture;- }+ seoFilename = CommonHelper.EnsureMaximumLength(seoFilename, 100);++ if (validateBinary && pictureBinary != null)+ pictureBinary = ValidatePicture(pictureBinary, mimeType);- /// <summary>- /// Updates the picture- /// </summary>- /// <param name="picture">Picture</param>- /// <returns>Picture</returns>- public virtual async Task<Picture> UpdatePicture(Picture picture)+ var picture = await GetPictureById(pictureId);+ if (picture == null)+ return null;++ //delete old thumbs if a picture has been changed+ if (seoFilename != picture.SeoFilename || pictureBinary != null)+ await DeletePictureThumbs(picture);++ if (pictureBinary != null){- ArgumentNullException.ThrowIfNull(picture);+ picture.PictureBinary = _storageSettings.PictureStoreInDb ? pictureBinary : Array.Empty<byte>();+ await _pictureRepository.UpdateField(picture.Id, x => x.PictureBinary, picture.PictureBinary);+ }- await _pictureRepository.UpdateAsync(picture);+ picture.MimeType = mimeType;+ await _pictureRepository.UpdateField(picture.Id, x => x.MimeType, picture.MimeType);- //event notification- await _mediator.EntityUpdated(picture);+ picture.SeoFilename = seoFilename;+ await _pictureRepository.UpdateField(picture.Id, x => x.SeoFilename, picture.SeoFilename);- //clare cache- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PICTURE_BY_ID, picture.Id));+ picture.AltAttribute = altAttribute;+ await _pictureRepository.UpdateField(picture.Id, x => x.AltAttribute, picture.AltAttribute);- return picture;- }+ picture.TitleAttribute = titleAttribute;+ await _pictureRepository.UpdateField(picture.Id, x => x.TitleAttribute, picture.TitleAttribute);- /// <summary>- /// Updates the picture- /// </summary>- /// <param name="picture">Picture</param>- /// <param name="expression"></param>- /// <param name="value"></param>- /// <returns>Picture</returns>- public virtual async Task UpdatePictureField<T>(Picture picture, Expression<Func<Picture, T>> expression, T value)- {- ArgumentNullException.ThrowIfNull(picture);+ picture.Style = style;+ await _pictureRepository.UpdateField(picture.Id, x => x.Style, picture.Style);- await _pictureRepository.UpdateField(picture.Id, expression, value);+ picture.ExtraField = extraField;+ await _pictureRepository.UpdateField(picture.Id, x => x.ExtraField, picture.ExtraField);- //event notification- await _mediator.EntityUpdated(picture);+ picture.IsNew = isNew;+ await _pictureRepository.UpdateField(picture.Id, x => x.IsNew, picture.IsNew);- //clare cache- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PICTURE_BY_ID, picture.Id));+ if (!_storageSettings.PictureStoreInDb && pictureBinary != null)+ await SavePictureInFile(picture.Id, pictureBinary, mimeType);- }+ //event notification+ await _mediator.EntityUpdated(picture);- /// <summary>- /// Save picture on file system- /// </summary>- /// <param name="pictureId">Picture identifier</param>- /// <param name="pictureBinary">Picture binary</param>- /// <param name="mimeType">MIME type</param>- public virtual Task SavePictureInFile(string pictureId, byte[] pictureBinary, string mimeType)- {- var lastPart = GetFileExtensionFromMimeType(mimeType);- var fileName = $"{pictureId}_0.{lastPart}";- var dirPath = _mediaFileStore.GetDirectoryInfo(CommonPath.ImagePath);- if (dirPath != null)- {- var filepath = _mediaFileStore.Combine(dirPath.PhysicalPath, fileName);- File.WriteAllBytes(filepath, pictureBinary);- }- else- _logger.LogError("Directory path not exist");+ //clare cache+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PICTURE_BY_ID, picture.Id));- return Task.CompletedTask;- }+ return picture;+ }- /// <summary>- /// Updates a SEO filename of a picture- /// </summary>- /// <param name="picture">The picture</param>- /// <param name="seoFilename">The SEO filename</param>- /// <returns>Picture</returns>- public virtual async Task<Picture> SetSeoFilename(Picture picture, string seoFilename)- {- if (picture == null)- throw new ArgumentException("No picture found with the specified id");+ /// <summary>+ /// Updates the picture+ /// </summary>+ /// <param name="picture">Picture</param>+ /// <returns>Picture</returns>+ public virtual async Task<Picture> UpdatePicture(Picture picture)+ {+ ArgumentNullException.ThrowIfNull(picture);- //update if it has been changed- if (seoFilename == picture.SeoFilename) return picture;- //update SeoFilename picture- picture.SeoFilename = seoFilename;- await UpdatePictureField(picture, p => p.SeoFilename, seoFilename);+ await _pictureRepository.UpdateAsync(picture);- //event notification- await _mediator.EntityUpdated(picture);+ //event notification+ await _mediator.EntityUpdated(picture);- //clare cache- await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PICTURE_BY_ID, picture.Id));- return picture;+ //clare cache+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PICTURE_BY_ID, picture.Id));++ return picture;+ }++ /// <summary>+ /// Updates the picture+ /// </summary>+ /// <param name="picture">Picture</param>+ /// <param name="expression"></param>+ /// <param name="value"></param>+ /// <returns>Picture</returns>+ public virtual async Task UpdatePictureField<T>(Picture picture, Expression<Func<Picture, T>> expression, T value)+ {+ ArgumentNullException.ThrowIfNull(picture);++ await _pictureRepository.UpdateField(picture.Id, expression, value);++ //event notification+ await _mediator.EntityUpdated(picture);++ //clare cache+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PICTURE_BY_ID, picture.Id));+ }++ /// <summary>+ /// Save picture on file system+ /// </summary>+ /// <param name="pictureId">Picture identifier</param>+ /// <param name="pictureBinary">Picture binary</param>+ /// <param name="mimeType">MIME type</param>+ public virtual Task SavePictureInFile(string pictureId, byte[] pictureBinary, string mimeType)+ {+ var lastPart = GetFileExtensionFromMimeType(mimeType);+ var fileName = $"{pictureId}_0.{lastPart}";+ var dirPath = _mediaFileStore.GetDirectoryInfo(CommonPath.ImagePath);+ if (dirPath != null)+ {+ var filepath = _mediaFileStore.Combine(dirPath.PhysicalPath, fileName);+ File.WriteAllBytes(filepath, pictureBinary);+ }+ else+ {+ _logger.LogError("Directory path not exist");}- /// <summary>- /// Validates input picture dimensions- /// </summary>- /// <param name="byteArray">Picture binary</param>- /// <param name="mimeType">MIME type</param>- /// <returns>Picture binary or throws an exception</returns>- public virtual byte[] ValidatePicture(byte[] byteArray, string mimeType)+ return Task.CompletedTask;+ }++ /// <summary>+ /// Updates a SEO filename of a picture+ /// </summary>+ /// <param name="picture">The picture</param>+ /// <param name="seoFilename">The SEO filename</param>+ /// <returns>Picture</returns>+ public virtual async Task<Picture> SetSeoFilename(Picture picture, string seoFilename)+ {+ if (picture == null)+ throw new ArgumentException("No picture found with the specified id");++ //update if it has been changed+ if (seoFilename == picture.SeoFilename) return picture;+ //update SeoFilename picture+ picture.SeoFilename = seoFilename;+ await UpdatePictureField(picture, p => p.SeoFilename, seoFilename);++ //event notification+ await _mediator.EntityUpdated(picture);++ //clare cache+ await _cacheBase.RemoveByPrefix(string.Format(CacheKey.PICTURE_BY_ID, picture.Id));+ return picture;+ }++ /// <summary>+ /// Validates input picture dimensions+ /// </summary>+ /// <param name="byteArray">Picture binary</param>+ /// <param name="mimeType">MIME type</param>+ /// <returns>Picture binary or throws an exception</returns>+ public virtual byte[] ValidatePicture(byte[] byteArray, string mimeType)+ {+ try{- try+ var format = EncodedImageFormat(mimeType);+ using (new MemoryStream(byteArray)){- var format = EncodedImageFormat(mimeType);- using (new MemoryStream(byteArray))+ using (var image = SKBitmap.Decode(byteArray)){- using (var image = SKBitmap.Decode(byteArray))+ if (image.Width >= image.Height){- if (image.Width >= image.Height)- {- //horizontal rectangle or square- if (image.Width <= _mediaSettings.MaximumImageSize ||- image.Height <= _mediaSettings.MaximumImageSize) return byteArray;- var resizedPicture = ApplyResize(image, format, _mediaSettings.MaximumImageSize);- if (resizedPicture != null)- byteArray = resizedPicture;- }- else if (image.Width < image.Height)- {- //vertical rectangle- if (image.Width <= _mediaSettings.MaximumImageSize) return byteArray;- var resizedPicture = ApplyResize(image, format, _mediaSettings.MaximumImageSize);- if (resizedPicture != null)- byteArray = resizedPicture;-- }- return byteArray;+ //horizontal rectangle or square+ if (image.Width <= _mediaSettings.MaximumImageSize ||+ image.Height <= _mediaSettings.MaximumImageSize) return byteArray;+ var resizedPicture = ApplyResize(image, format, _mediaSettings.MaximumImageSize);+ if (resizedPicture != null)+ byteArray = resizedPicture;}+ else if (image.Width < image.Height)+ {+ //vertical rectangle+ if (image.Width <= _mediaSettings.MaximumImageSize) return byteArray;+ var resizedPicture = ApplyResize(image, format, _mediaSettings.MaximumImageSize);+ if (resizedPicture != null)+ byteArray = resizedPicture;+ }++ return byteArray;}}- catch- {- return byteArray;- }}---- /// <summary>- /// Convert picture- /// </summary>- /// <param name="pictureBinary">Picture binary</param>- /// <param name="imageQuality">Image quality</param>- /// <param name="format">Format</param>- /// <returns>Picture binary or throws an exception</returns>- public virtual byte[] ConvertPicture(byte[] pictureBinary, int imageQuality, string format = "Webp")+ catch{- Enum.TryParse(typeof(SKEncodedImageFormat), format, out var skFormat);- skFormat ??= SKEncodedImageFormat.Webp;-- using var image = SKBitmap.Decode(pictureBinary);- SKData d = SKImage.FromBitmap(image).Encode((SKEncodedImageFormat)skFormat, imageQuality);- return d.ToArray();+ return byteArray;}+ }- private SKEncodedImageFormat EncodedImageFormat(string mimetype)- {- const SKEncodedImageFormat defaultFormat = SKEncodedImageFormat.Jpeg;- if (string.IsNullOrEmpty(mimetype))- return defaultFormat;+ /// <summary>+ /// Convert picture+ /// </summary>+ /// <param name="pictureBinary">Picture binary</param>+ /// <param name="imageQuality">Image quality</param>+ /// <param name="format">Format</param>+ /// <returns>Picture binary or throws an exception</returns>+ public virtual byte[] ConvertPicture(byte[] pictureBinary, int imageQuality, string format = "Webp")+ {+ Enum.TryParse(typeof(SKEncodedImageFormat), format, out var skFormat);+ skFormat ??= SKEncodedImageFormat.Webp;- mimetype = mimetype.ToLower();+ using var image = SKBitmap.Decode(pictureBinary);+ var d = SKImage.FromBitmap(image).Encode((SKEncodedImageFormat)skFormat, imageQuality);+ return d.ToArray();+ }- if (mimetype.Contains("jpeg"))- return defaultFormat;-- if (mimetype.Contains("jpg"))- return defaultFormat;-- if (mimetype.Contains("pjpeg"))- return defaultFormat;- if (mimetype.Contains("png"))- return SKEncodedImageFormat.Png;+ private SKEncodedImageFormat EncodedImageFormat(string mimetype)+ {+ const SKEncodedImageFormat defaultFormat = SKEncodedImageFormat.Jpeg;+ if (string.IsNullOrEmpty(mimetype))+ return defaultFormat;- if (mimetype.Contains("webp"))- return SKEncodedImageFormat.Webp;+ mimetype = mimetype.ToLower();- if (mimetype.Contains("wbmp"))- return SKEncodedImageFormat.Wbmp;+ if (mimetype.Contains("jpeg"))+ return defaultFormat;- if (mimetype.Contains("gif"))- return SKEncodedImageFormat.Gif;+ if (mimetype.Contains("jpg"))+ return defaultFormat;- //if mime type is BMP format then happens error with convert picture- if (mimetype.Contains("bmp"))- return SKEncodedImageFormat.Png;+ if (mimetype.Contains("pjpeg"))+ return defaultFormat;- return mimetype.Contains("ico") ? SKEncodedImageFormat.Ico : defaultFormat;- }+ if (mimetype.Contains("png"))+ return SKEncodedImageFormat.Png;- private byte[] ApplyResize(SKBitmap image, SKEncodedImageFormat format, int targetSize)- {- ArgumentNullException.ThrowIfNull(image);+ if (mimetype.Contains("webp"))+ return SKEncodedImageFormat.Webp;- if (targetSize <= 0)- {- targetSize = 800;- }- float width, height;- if (image.Height > image.Width)- {- // portrait- width = image.Width * (targetSize / (float)image.Height);- height = targetSize;- }- else- {- // landscape or square- width = targetSize;- height = image.Height * (targetSize / (float)image.Width);- }+ if (mimetype.Contains("wbmp"))+ return SKEncodedImageFormat.Wbmp;- if ((int)width == 0 || (int)height == 0)- {- width = image.Width;- height = image.Height;- }+ if (mimetype.Contains("gif"))+ return SKEncodedImageFormat.Gif;- try- {- using var resized = image.Resize(new SKImageInfo((int)width, (int)height), SKFilterQuality.High);- using var resImage = SKImage.FromBitmap(resized);- var skData = resImage.Encode(format, _mediaSettings.ImageQuality);- return skData?.ToArray();- }- catch (Exception ex)- {- _logger.LogError(ex, "ApplyResize - format {Format}", format);- return null;- }+ //if mime type is BMP format then happens error with convert picture+ if (mimetype.Contains("bmp"))+ return SKEncodedImageFormat.Png;+ return mimetype.Contains("ico") ? SKEncodedImageFormat.Ico : defaultFormat;+ }++ private byte[] ApplyResize(SKBitmap image, SKEncodedImageFormat format, int targetSize)+ {+ ArgumentNullException.ThrowIfNull(image);+ if (targetSize <= 0) targetSize = 800;+ float width, height;+ if (image.Height > image.Width)+ {+ // portrait+ width = image.Width * (targetSize / (float)image.Height);+ height = targetSize;+ }+ else+ {+ // landscape or square+ width = targetSize;+ height = image.Height * (targetSize / (float)image.Width);}- #endregion+ if ((int)width == 0 || (int)height == 0)+ {+ width = image.Width;+ height = image.Height;+ }+ try+ {+ using var resized = image.Resize(new SKImageInfo((int)width, (int)height), SKFilterQuality.High);+ using var resImage = SKImage.FromBitmap(resized);+ var skData = resImage.Encode(format, _mediaSettings.ImageQuality);+ return skData?.ToArray();+ }+ catch (Exception ex)+ {+ _logger.LogError(ex, "ApplyResize - format {Format}", format);+ return null;+ }}++ #endregion}\ No newline at end of filediff --git a/src/Business/Grand.Business.Storage/Startup/StartupApplication.cs b/src/Business/Grand.Business.Storage/Startup/StartupApplication.csindex a9c9cb048..458544de9 100644--- a/src/Business/Grand.Business.Storage/Startup/StartupApplication.cs+++ b/src/Business/Grand.Business.Storage/Startup/StartupApplication.cs@@ -8,51 +8,47 @@ using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Business.Storage.Startup+namespace Grand.Business.Storage.Startup;++public class StartupApplication : IStartupApplication{- public class StartupApplication : IStartupApplication+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration){- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- services.AddScoped<IDownloadService, DownloadService>();-- //picture service- var azureConfig = new AzureConfig();- configuration.GetSection("Azure").Bind(azureConfig);- var useAzureBlobStorage = !string.IsNullOrEmpty(azureConfig.AzureBlobStorageConnectionString);-- var amazonConfig = new AmazonConfig();- configuration.GetSection("Amazon").Bind(amazonConfig);- var useAmazonBlobStorage = !string.IsNullOrEmpty(amazonConfig.AmazonAwsAccessKeyId) && !string.IsNullOrEmpty(amazonConfig.AmazonAwsSecretAccessKey) && !string.IsNullOrEmpty(amazonConfig.AmazonBucketName) && !string.IsNullOrEmpty(amazonConfig.AmazonRegion);-- if (useAzureBlobStorage)- {- //Windows Azure BLOB- services.AddScoped<IPictureService, AzurePictureService>();- }- else if (useAmazonBlobStorage)- {- //Amazon S3 Simple Storage Service- services.AddScoped<IPictureService, AmazonPictureService>();- }- else- {- //standard file system- services.AddScoped<IPictureService, PictureService>();- }-- services.AddScoped<IMediaFileStore>(serviceProvider =>- {- var fileStore = new FileSystemStore(CommonPath.WebRootPath);- return new DefaultMediaFileStore(fileStore);- });-- }- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ services.AddScoped<IDownloadService, DownloadService>();++ //picture service+ var azureConfig = new AzureConfig();+ configuration.GetSection("Azure").Bind(azureConfig);+ var useAzureBlobStorage = !string.IsNullOrEmpty(azureConfig.AzureBlobStorageConnectionString);++ var amazonConfig = new AmazonConfig();+ configuration.GetSection("Amazon").Bind(amazonConfig);+ var useAmazonBlobStorage = !string.IsNullOrEmpty(amazonConfig.AmazonAwsAccessKeyId) &&+ !string.IsNullOrEmpty(amazonConfig.AmazonAwsSecretAccessKey) &&+ !string.IsNullOrEmpty(amazonConfig.AmazonBucketName) &&+ !string.IsNullOrEmpty(amazonConfig.AmazonRegion);++ if (useAzureBlobStorage)+ //Windows Azure BLOB+ services.AddScoped<IPictureService, AzurePictureService>();+ else if (useAmazonBlobStorage)+ //Amazon S3 Simple Storage Service+ services.AddScoped<IPictureService, AmazonPictureService>();+ else+ //standard file system+ services.AddScoped<IPictureService, PictureService>();++ services.AddScoped<IMediaFileStore>(serviceProvider =>{+ var fileStore = new FileSystemStore(CommonPath.WebRootPath);+ return new DefaultMediaFileStore(fileStore);+ });+ }- }- public int Priority => 100;- public bool BeforeConfigure => false;+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {}-}++ public int Priority => 100;+ public bool BeforeConfigure => false;+}\ No newline at end of file