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
Share runtime-written files across instances via Application:MediaPath (#865)
Krzysztof Pajake69893b8b536
diff --git a/Dockerfile b/Dockerfileindex 92e51d43e..3b4bb7bd3 100644--- a/Dockerfile+++ b/Dockerfile@@ -30,7 +30,7 @@ EXPOSE 8080WORKDIR /appCOPY --from=build-env /app/build/release .-RUN chown -R app:app /app/App_Data /app/wwwroot /app/Plugins+RUN mkdir -p /app/media && chown -R app:app /app/App_Data /app/wwwroot /app/Plugins /app/mediaUSER appdiff --git a/README.md b/README.mdindex fc7614a23..0f8840a04 100644--- a/README.md+++ b/README.md@@ -133,6 +133,28 @@ If you want to download the latest stable version of GrandNode please use the fodocker pull grandnode/grandnode2:x.xx```+#### Running more than one instance++Files GrandNode writes at runtime (sitemap XML files, custom CSS/JS, uploaded images, thumbnails, the push+service worker) live in `wwwroot` by default, so with several instances each one only sees its own. Point+`Application:MediaPath` at a volume shared by all instances (ReadWriteMany in Kubernetes: Azure Files, EFS, NFS):++```bash+docker run -d -p 80:8080 --name grandnode2 --link mongodb:mongo \+ -e Application__MediaPath=/app/media -v grandnode_media:/app/media \+ -v grandnode_appdata:/app/App_Data grandnode/grandnode2+```++Files that ship with the build stay in `wwwroot` and are used until the shop overwrites them. When switching an+existing installation, **move** (not copy) `wwwroot/assets/custom`, `wwwroot/assets/images/uploaded`,+`wwwroot/sitemap*.xml`, `wwwroot/firebase-messaging-sw.js` and, with pictures stored on disk, the+`wwwroot/assets/images/*_0.*` originals into the same paths under the media path, then stop mounting the old+`wwwroot/assets/images` volume. With the `Directory` setting configured, both sides carry it as a prefix: move+`wwwroot/{Directory}/assets/custom` to `{MediaPath}/{Directory}/assets/custom`, and so on. Without the move, each+instance serves its own copy of the sitemap until the sitemap task runs again, and of the push service worker until+the push notification settings are saved again. A file left behind in `wwwroot` keeps being served after it is+deleted in the admin, because the shop only deletes on the media path. Thumbnails are regenerated on the media path.+* Open locally in an IDEExtract the source code package downloaded from the Releases tab to a folder (ordiff --git a/src/Business/Grand.Business.Storage/Services/AtomicFile.cs b/src/Business/Grand.Business.Storage/Services/AtomicFile.csnew file mode 100644index 000000000..5ea3ecf5e--- /dev/null+++ b/src/Business/Grand.Business.Storage/Services/AtomicFile.cs@@ -0,0 +1,68 @@+using System.Text;++namespace Grand.Business.Storage.Services;++/// <summary>+/// Writes a file so a concurrent reader - another instance on a shared volume, or the static file+/// middleware - sees either the old or the new content, never a half-written file+/// </summary>+public static class AtomicFile+{+ public static async Task WriteAllBytesAsync(string path, byte[] bytes)+ {+ var tempPath = TempPathFor(path);+ try+ {+ await File.WriteAllBytesAsync(tempPath, bytes);+ await Replace(tempPath, path);+ }+ finally+ {+ if (File.Exists(tempPath)) File.Delete(tempPath);+ }+ }++ public static async Task WriteAllTextAsync(string path, string text)+ {+ var tempPath = TempPathFor(path);+ try+ {+ await File.WriteAllTextAsync(tempPath, text, Encoding.UTF8);+ await Replace(tempPath, path);+ }+ finally+ {+ if (File.Exists(tempPath)) File.Delete(tempPath);+ }+ }++ //same directory, so the rename never crosses a file system+ private static string TempPathFor(string path) => $"{path}.{Guid.NewGuid():N}.tmp";++ //Windows refuses to rename over a file a reader holds open; wait for the reader instead of overwriting in+ //place, which would expose a half-written file+ private const int ReplaceAttempts = 20;+ private static readonly TimeSpan ReplaceRetryDelay = TimeSpan.FromMilliseconds(50);++ private static async Task Replace(string tempPath, string path)+ {+ for (var attempt = 1;; attempt++)+ try+ {+ File.Move(tempPath, path, true);+ return;+ }+ catch (Exception ex) when (attempt < ReplaceAttempts && IsSharingViolation(ex))+ {+ await Task.Delay(ReplaceRetryDelay);+ }+ }++ private static bool IsSharingViolation(Exception ex)+ {+ //ERROR_SHARING_VIOLATION (32) / ERROR_LOCK_VIOLATION (33) come as IOException, ERROR_ACCESS_DENIED as+ //UnauthorizedAccessException when the target is open+ return ex is UnauthorizedAccessException ||+ (ex is IOException && (ex.HResult & 0xFFFF) is 32 or 33);+ }+}diff --git a/src/Business/Grand.Business.Storage/Services/FileSystemStore.cs b/src/Business/Grand.Business.Storage/Services/FileSystemStore.csindex fabcd8f06..2b01ebc52 100644--- a/src/Business/Grand.Business.Storage/Services/FileSystemStore.cs+++ b/src/Business/Grand.Business.Storage/Services/FileSystemStore.cs@@ -234,10 +234,7 @@ public class FileSystemStore : IFileStore{var physicalPath = GetPhysicalPath(path);- if (!File.Exists(physicalPath))- File.Create(physicalPath).Close();-- return File.WriteAllTextAsync(physicalPath, text, Encoding.UTF8);+ return AtomicFile.WriteAllTextAsync(physicalPath, text);}diff --git a/src/Business/Grand.Business.Storage/Services/LayeredFileStore.cs b/src/Business/Grand.Business.Storage/Services/LayeredFileStore.csnew file mode 100644index 000000000..076d8c32a--- /dev/null+++ b/src/Business/Grand.Business.Storage/Services/LayeredFileStore.cs@@ -0,0 +1,106 @@+using Grand.Business.Core.Interfaces.Storage;+using Microsoft.Extensions.FileProviders.Physical;++namespace Grand.Business.Storage.Services;++/// <summary>+/// A writable primary store over a read-only fallback. Files written at runtime go to the primary+/// (a volume shared by every instance); files that ship with the build are still found in the fallback (wwwroot).+/// </summary>+public class LayeredFileStore : IFileStore+{+ private readonly IFileStore _fallback;+ private readonly IFileStore _primary;+ private readonly string[] _primaryOnlyPaths;++ /// <param name="primary">Writable store</param>+ /// <param name="fallback">Read-only store consulted when a file is missing in the primary</param>+ /// <param name="primaryOnlyPaths">+ /// Directories whose files are never read from the fallback (generated files a stale copy+ /// would shadow)+ /// </param>+ public LayeredFileStore(IFileStore primary, IFileStore fallback, IEnumerable<string> primaryOnlyPaths)+ {+ _primary = primary;+ _fallback = fallback;+ _primaryOnlyPaths = primaryOnlyPaths.Select(p => this.NormalizePath(p)).ToArray();+ }++ public async Task<IFileStoreEntry> GetFileInfo(string path)+ {+ return await _primary.GetFileInfo(path)+ ?? (IsPrimaryOnly(path) ? null : await _fallback.GetFileInfo(path));+ }++ public IFileStoreEntry GetDirectoryInfo(string path)+ {+ var entry = _primary.GetDirectoryInfo(path);+ if (entry != null) return entry;++ if (_fallback.GetDirectoryInfo(path) == null) return null;++ //the directory ships with the build but is not on the volume yet: create it, so writers land on the volume+ _primary.TryCreateDirectory(path);+ return _primary.GetDirectoryInfo(path);+ }++ public Task<PhysicalDirectoryInfo> GetPhysicalDirectoryInfo(string directoryPath)+ {+ return GetDirectoryInfo(directoryPath) == null+ ? Task.FromResult<PhysicalDirectoryInfo>(null)+ : _primary.GetPhysicalDirectoryInfo(directoryPath);+ }++ public IList<IFileStoreEntry> GetDirectoryContent(string path = null, bool includeSubDirectories = false,+ bool listDirectories = true, bool listFiles = true)+ {+ var primaryEntries = _primary.GetDirectoryContent(path, includeSubDirectories, listDirectories, listFiles);+ if (IsPrimaryOnly(path)) return primaryEntries;++ var primaryPaths = primaryEntries.Select(e => e.Path).ToHashSet(StringComparer.OrdinalIgnoreCase);+ return primaryEntries+ .Concat(_fallback.GetDirectoryContent(path, includeSubDirectories, listDirectories, listFiles)+ .Where(e => !primaryPaths.Contains(e.Path)))+ .ToList();+ }++ public bool TryCreateDirectory(string path) => _primary.TryCreateDirectory(path);++ public Task<bool> TryRenameDirectory(string path, string newName) => _primary.TryRenameDirectory(path, newName);++ public Task<bool> TryDeleteFile(string path) => _primary.TryDeleteFile(path);++ public Task<bool> TryDeleteDirectory(string path) => _primary.TryDeleteDirectory(path);++ public Task MoveFile(string oldPath, string newPath) => _primary.MoveFile(oldPath, newPath);++ public Task CopyFile(string srcPath, string dstPath) => _primary.CopyFile(srcPath, dstPath);++ public Task RenameFile(string file, string newName) => _primary.RenameFile(file, newName);++ public async Task<Stream> GetFileStream(string path) => await (await ReadSource(path)).GetFileStream(path);++ public Task<Stream> GetFileStream(IFileStoreEntry fileStoreEntry) => GetFileStream(fileStoreEntry.Path);++ public Task<string> CreateFileFromStream(string path, Stream inputStream, bool overwrite = false)+ {+ return _primary.CreateFileFromStream(path, inputStream, overwrite);+ }++ public async Task<string> ReadAllText(string path) => await (await ReadSource(path)).ReadAllText(path);++ public Task WriteAllText(string path, string text) => _primary.WriteAllText(path, text);++ private async Task<IFileStore> ReadSource(string path)+ {+ return IsPrimaryOnly(path) || await _primary.GetFileInfo(path) != null ? _primary : _fallback;+ }++ private bool IsPrimaryOnly(string path)+ {+ var normalized = this.NormalizePath(path) ?? "";+ return _primaryOnlyPaths.Any(p =>+ normalized.Equals(p, StringComparison.OrdinalIgnoreCase) ||+ normalized.StartsWith(p + "/", StringComparison.OrdinalIgnoreCase));+ }+}diff --git a/src/Business/Grand.Business.Storage/Services/MediaFileStoreFactory.cs b/src/Business/Grand.Business.Storage/Services/MediaFileStoreFactory.csnew file mode 100644index 000000000..703576ee4--- /dev/null+++ b/src/Business/Grand.Business.Storage/Services/MediaFileStoreFactory.cs@@ -0,0 +1,31 @@+using Grand.Business.Core.Interfaces.Storage;++namespace Grand.Business.Storage.Services;++public static class MediaFileStoreFactory+{+ /// <summary>+ /// Directories whose files are never read from wwwroot once a media path is set: thumbs are regenerated+ /// and deleted on the volume only, so a stale copy in wwwroot would outlive a picture change+ /// </summary>+ public static readonly IReadOnlyList<string> PrimaryOnlyPaths = Array.AsReadOnly(new[] { "assets/images/thumbs" });++ /// <summary>+ /// Creates the file store behind IMediaFileStore+ /// </summary>+ /// <param name="webRootPath">wwwroot physical path</param>+ /// <param name="mediaRootPath">Shared media physical path; null or empty keeps everything in wwwroot</param>+ /// <param name="directory">Optional per-installation subdirectory (the "Directory" config value)</param>+ /// <remarks>+ /// Runs once per request scope, so it does not touch the file system; the media directory is created+ /// at startup (MediaRootFileProvider.Apply)+ /// </remarks>+ public static IFileStore Create(string webRootPath, string mediaRootPath, string directory)+ {+ var webRootStore = new FileSystemStore(Path.Combine(webRootPath, directory ?? ""));+ if (string.IsNullOrEmpty(mediaRootPath)) return webRootStore;++ var mediaStore = new FileSystemStore(Path.Combine(mediaRootPath, directory ?? ""));+ return new LayeredFileStore(mediaStore, webRootStore, PrimaryOnlyPaths);+ }+}diff --git a/src/Business/Grand.Business.Storage/Services/PictureService.cs b/src/Business/Grand.Business.Storage/Services/PictureService.csindex c857f9714..77a551709 100644--- a/src/Business/Grand.Business.Storage/Services/PictureService.cs+++ b/src/Business/Grand.Business.Storage/Services/PictureService.cs@@ -198,7 +198,7 @@ public class PictureService : IPictureService/// </summary>/// <param name="thumbFileName">Thumb file name</param>/// <param name="binary">Picture binary</param>- protected virtual Task SaveThumb(string thumbFileName, byte[] binary)+ protected virtual async Task SaveThumb(string thumbFileName, byte[] binary){try{@@ -213,7 +213,7 @@ public class PictureService : IPictureServiceif (dirThumb != null){var file = _mediaFileStore.Combine(dirThumb.PhysicalPath, thumbFileName);- File.WriteAllBytes(file, binary ?? []);+ await AtomicFile.WriteAllBytesAsync(file, binary ?? []);}else{@@ -224,8 +224,6 @@ public class PictureService : IPictureService{_logger.LogError(ex, ex.Message);}-- return Task.CompletedTask;}#endregion@@ -275,21 +273,10 @@ public class PictureService : IPictureServiceif (!string.IsNullOrEmpty(thumbFilePath))return GetThumbUrl(thumbFileName, storeLocation);- using (var mutex = new Mutex(false, thumbFileName))- {- mutex.WaitOne();- try- {- using var image = SKBitmap.Decode(filePath);- var pictureBinary = ApplyResize(image, EncodedImageFormat(fileExtension), targetSize);- if (pictureBinary != null)- await SaveThumb(thumbFileName, pictureBinary);- }- finally- {- mutex.ReleaseMutex();- }- }+ using var image = SKBitmap.Decode(filePath);+ var pictureBinary = ApplyResize(image, EncodedImageFormat(fileExtension), targetSize);+ if (pictureBinary != null)+ await SaveThumb(thumbFileName, pictureBinary);var url = GetThumbUrl(thumbFileName, storeLocation);return url;}@@ -357,16 +344,7 @@ public class PictureService : IPictureServicevar pictureBinary = await LoadPictureBinary(picture);- using var mutex = new Mutex(false, thumbFileName);- mutex.WaitOne();- try- {- await SaveThumb(thumbFileName, pictureBinary);- }- finally- {- mutex.ReleaseMutex();- }+ await SaveThumb(thumbFileName, pictureBinary);}else{@@ -381,30 +359,21 @@ public class PictureService : IPictureServicevar pictureBinary = await LoadPictureBinary(picture);- using var mutex = new Mutex(false, thumbFileName);- mutex.WaitOne();- try+ if (pictureBinary != null){- if (pictureBinary != null)+ try{- try- {- using var image = SKBitmap.Decode(pictureBinary);- var resizedBinary = ApplyResize(image, EncodedImageFormat(picture.MimeType), targetSize);- if (resizedBinary != null)- pictureBinary = resizedBinary;- }- catch- {- // ignored- }+ 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);- }- finally- {- mutex.ReleaseMutex();}+ await SaveThumb(thumbFileName, pictureBinary);}return GetThumbUrl(thumbFileName, storeLocation);@@ -493,8 +462,8 @@ public class PictureService : IPictureServicevar lastPart = GetFileExtensionFromMimeType(picture.MimeType);var fileName = $"{picture.Id}_0.{lastPart}";- var filePath = await GetPicturePhysicalPath(fileName);- if (!string.IsNullOrEmpty(filePath)) File.Delete(filePath);+ //through the store: with a media path it deletes on the volume only, never in read-only wwwroot+ await _mediaFileStore.TryDeleteFile(_mediaFileStore.Combine(ImagePath, fileName));}public virtual async Task ClearThumbs()@@ -701,7 +670,7 @@ public class PictureService : IPictureService/// <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)+ public virtual async Task SavePictureInFile(string pictureId, byte[] pictureBinary, string mimeType){var lastPart = GetFileExtensionFromMimeType(mimeType);var fileName = $"{pictureId}_0.{lastPart}";@@ -709,14 +678,12 @@ public class PictureService : IPictureServiceif (dirPath != null){var filepath = _mediaFileStore.Combine(dirPath.PhysicalPath, fileName);- File.WriteAllBytes(filepath, pictureBinary);+ await AtomicFile.WriteAllBytesAsync(filepath, pictureBinary);}else{_logger.LogError("Directory path not exist");}-- return Task.CompletedTask;}/// <summary>diff --git a/src/Business/Grand.Business.Storage/Startup/StartupApplication.cs b/src/Business/Grand.Business.Storage/Startup/StartupApplication.csindex 73d82e44c..f383aa358 100644--- a/src/Business/Grand.Business.Storage/Startup/StartupApplication.cs+++ b/src/Business/Grand.Business.Storage/Startup/StartupApplication.cs@@ -41,8 +41,10 @@ public class StartupApplication : IStartupApplicationservices.AddScoped<IMediaFileStore>(serviceProvider =>{var webHostEnvironment = serviceProvider.GetRequiredService<IWebHostEnvironment>();- var param = configuration[CommonPath.DirectoryParam];- var fileStore = new FileSystemStore(Path.Combine(webHostEnvironment.WebRootPath, param ?? ""));+ var appConfig = serviceProvider.GetRequiredService<AppConfig>();+ var fileStore = MediaFileStoreFactory.Create(webHostEnvironment.WebRootPath,+ appConfig.GetMediaRootPath(webHostEnvironment.ContentRootPath),+ configuration[CommonPath.DirectoryParam]);return new DefaultMediaFileStore(fileStore);});}diff --git a/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs b/src/Core/Grand.Infrastructure/Configuration/AppConfig.csindex 735ac8f01..126775092 100644--- a/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs@@ -39,4 +39,11 @@ public class AppConfig/// Gets or sets the value to enable a middleware for logging additional information about CurrentCustomer and store/// </summary>public bool EnableContextLoggingMiddleware { get; set; }++ /// <summary>+ /// Gets or sets the directory for files the application writes at runtime (custom css/js, uploaded images,+ /// thumbnails, sitemap xml files). Empty keeps them in wwwroot. With more than one instance, point every+ /// instance at the same shared volume. A relative path is resolved against the content root.+ /// </summary>+ public string MediaPath { get; set; }}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/AppConfigExtensions.cs b/src/Core/Grand.Infrastructure/Configuration/AppConfigExtensions.csnew file mode 100644index 000000000..3d61e26f7--- /dev/null+++ b/src/Core/Grand.Infrastructure/Configuration/AppConfigExtensions.cs@@ -0,0 +1,49 @@+using Grand.SharedKernel.Extensions;++namespace Grand.Infrastructure.Configuration;++public static class AppConfigExtensions+{+ /// <summary>+ /// Resolves <see cref="AppConfig.MediaPath" /> to a full physical path+ /// </summary>+ /// <param name="appConfig">Application config</param>+ /// <param name="contentRootPath">Content root a relative media path is resolved against</param>+ /// <returns>The full path, or null when no media path is configured</returns>+ /// <exception cref="InvalidOperationException">+ /// The media path is the content root, one of its parents, or App_Data: the media root is served+ /// at "/", so it would publish appsettings.json and Settings.cfg+ /// </exception>+ public static string GetMediaRootPath(this AppConfig appConfig, string contentRootPath)+ {+ ArgumentNullException.ThrowIfNull(appConfig);++ if (string.IsNullOrWhiteSpace(appConfig.MediaPath)) return null;++ var mediaRoot = Path.GetFullPath(appConfig.MediaPath, contentRootPath);+ var contentRoot = Path.GetFullPath(contentRootPath);++ if (IsSameOrParentOf(mediaRoot, contentRoot) ||+ IsSame(mediaRoot, Path.Combine(contentRoot, CommonPath.AppData)))+ throw new InvalidOperationException(+ $"Application:MediaPath '{appConfig.MediaPath}' would publish application files; use a dedicated directory, e.g. App_Data/media.");++ return mediaRoot;+ }++ private static bool IsSame(string path, string other)+ {+ return string.Equals(Path.TrimEndingDirectorySeparator(path), Path.TrimEndingDirectorySeparator(other),+ StringComparison.OrdinalIgnoreCase);+ }++ private static bool IsSameOrParentOf(string parent, string child)+ {+ //a filesystem root ("/", "C:\", "\\server\share\") keeps its trailing separator; don't double it+ var parentWithSeparator = Path.EndsInDirectorySeparator(parent)+ ? parent+ : parent + Path.DirectorySeparatorChar;+ return IsSame(parent, child) ||+ child.StartsWith(parentWithSeparator, StringComparison.OrdinalIgnoreCase);+ }+}diff --git a/src/Tests/Grand.Business.Storage.Tests/Services/AtomicFileTests.cs b/src/Tests/Grand.Business.Storage.Tests/Services/AtomicFileTests.csnew file mode 100644index 000000000..6c559429f--- /dev/null+++ b/src/Tests/Grand.Business.Storage.Tests/Services/AtomicFileTests.cs@@ -0,0 +1,66 @@+using Grand.Business.Storage.Services;+using Microsoft.VisualStudio.TestTools.UnitTesting;++namespace Grand.Business.Storage.Tests.Services;++[TestClass]+public class AtomicFileTests+{+ private string _dir;++ [TestInitialize]+ public void Init()+ {+ _dir = Path.Combine(Path.GetTempPath(), "atomicfile-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(_dir);+ }++ [TestCleanup]+ public void Cleanup()+ {+ Directory.Delete(_dir, true);+ }++ [TestMethod]+ public async Task WriteAllBytes_NewFile_WritesContentAndLeavesNoTempFile()+ {+ //Arrange+ var path = Path.Combine(_dir, "thumb.jpg");+ //Act+ await AtomicFile.WriteAllBytesAsync(path, [1, 2, 3]);+ //Assert+ CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, File.ReadAllBytes(path));+ Assert.HasCount(1, Directory.GetFiles(_dir));+ }++ [TestMethod]+ public async Task WriteAllTextAsync_ExistingFile_OverwritesAndLeavesNoTempFile()+ {+ //Arrange+ var path = Path.Combine(_dir, "sitemap.xml");+ await File.WriteAllTextAsync(path, "old content that is longer than the new one");+ //Act+ await AtomicFile.WriteAllTextAsync(path, "new");+ //Assert+ Assert.AreEqual("new", await File.ReadAllTextAsync(path));+ Assert.HasCount(1, Directory.GetFiles(_dir));+ }++ [TestMethod]+ public async Task WriteAllBytes_TargetHeldOpenForReading_ReplacesOnceReaderCloses()+ {+ //Arrange - the static file middleware opens files with FileShare.ReadWrite+ var path = Path.Combine(_dir, "sitemap.xml");+ File.WriteAllBytes(path, [9]);+ var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);+ var closeReader = Task.Delay(200).ContinueWith(_ => reader.Dispose());++ //Act+ await AtomicFile.WriteAllBytesAsync(path, [1, 2]);+ await closeReader;++ //Assert+ CollectionAssert.AreEqual(new byte[] { 1, 2 }, File.ReadAllBytes(path));+ Assert.HasCount(1, Directory.GetFiles(_dir));+ }+}diff --git a/src/Tests/Grand.Business.Storage.Tests/Services/LayeredFileStoreTests.cs b/src/Tests/Grand.Business.Storage.Tests/Services/LayeredFileStoreTests.csnew file mode 100644index 000000000..dbea273a2--- /dev/null+++ b/src/Tests/Grand.Business.Storage.Tests/Services/LayeredFileStoreTests.cs@@ -0,0 +1,143 @@+using Grand.Business.Storage.Services;+using Microsoft.VisualStudio.TestTools.UnitTesting;++namespace Grand.Business.Storage.Tests.Services;++[TestClass]+public class LayeredFileStoreTests+{+ private string _media;+ private string _root;+ private LayeredFileStore _store;+ private string _webRoot;++ [TestInitialize]+ public void Init()+ {+ _root = Path.Combine(Path.GetTempPath(), "layered-" + Guid.NewGuid().ToString("N"));+ _media = Path.Combine(_root, "media");+ _webRoot = Path.Combine(_root, "wwwroot");+ Directory.CreateDirectory(_media);+ Directory.CreateDirectory(Path.Combine(_webRoot, "assets", "custom"));+ Directory.CreateDirectory(Path.Combine(_webRoot, "assets", "images", "thumbs"));+ File.WriteAllText(Path.Combine(_webRoot, "assets", "custom", "style.css"), "shipped");+ File.WriteAllText(Path.Combine(_webRoot, "assets", "images", "no-image.png"), "png");+ File.WriteAllText(Path.Combine(_webRoot, "assets", "images", "thumbs", "p1_100.jpg"), "stale");++ _store = new LayeredFileStore(new FileSystemStore(_media), new FileSystemStore(_webRoot),+ ["assets/images/thumbs"]);+ }++ [TestCleanup]+ public void Cleanup()+ {+ Directory.Delete(_root, true);+ }++ [TestMethod]+ public async Task GetFileInfo_OnlyInFallback_ReturnsFallbackEntry()+ {+ //Act+ var result = await _store.GetFileInfo("assets/images/no-image.png");+ //Assert+ Assert.IsNotNull(result);+ Assert.StartsWith(_webRoot, result.PhysicalPath);+ }++ [TestMethod]+ public async Task GetFileInfo_InBoth_ReturnsPrimary()+ {+ //Arrange+ Directory.CreateDirectory(Path.Combine(_media, "assets", "custom"));+ File.WriteAllText(Path.Combine(_media, "assets", "custom", "style.css"), "edited");+ //Act+ var result = await _store.GetFileInfo("assets/custom/style.css");+ //Assert+ Assert.StartsWith(_media, result.PhysicalPath);+ }++ [TestMethod]+ public async Task GetFileInfo_PrimaryOnlyPath_IgnoresFallback()+ {+ //Act+ var result = await _store.GetFileInfo(Path.Combine("assets", "images", "thumbs", "p1_100.jpg"));+ //Assert+ Assert.IsNull(result);+ }++ [TestMethod]+ public async Task ReadAllText_OnlyInFallback_ReadsFallback()+ {+ //Act+ var result = await _store.ReadAllText("assets/custom/style.css");+ //Assert+ Assert.AreEqual("shipped", result);+ }++ [TestMethod]+ public async Task WriteAllText_WritesPrimaryAndLeavesFallbackUntouched()+ {+ //Arrange+ _store.TryCreateDirectory("assets/custom");+ //Act+ await _store.WriteAllText("assets/custom/style.css", "edited");+ //Assert+ Assert.AreEqual("edited", await _store.ReadAllText("assets/custom/style.css"));+ Assert.AreEqual("shipped", File.ReadAllText(Path.Combine(_webRoot, "assets", "custom", "style.css")));+ }++ [TestMethod]+ public void GetDirectoryInfo_OnlyInFallback_CreatesItInPrimary()+ {+ //Act+ var result = _store.GetDirectoryInfo("assets/images");+ //Assert+ Assert.IsNotNull(result);+ Assert.StartsWith(_media, result.PhysicalPath);+ Assert.IsTrue(Directory.Exists(Path.Combine(_media, "assets", "images")));+ }++ [TestMethod]+ public void GetDirectoryInfo_UploadedShippedInWebRoot_FileManagerRootIsOnVolume()+ {+ //Arrange - wwwroot ships assets/images/uploaded with a placeholder.txt; elFinder takes PhysicalPath as its root+ Directory.CreateDirectory(Path.Combine(_webRoot, "assets", "images", "uploaded"));+ File.WriteAllText(Path.Combine(_webRoot, "assets", "images", "uploaded", "legacy.jpg"), "old");+ //Act+ var result = _store.GetDirectoryInfo(Path.Combine("assets", "images", "uploaded"));+ //Assert+ Assert.AreEqual(Path.Combine(_media, "assets", "images", "uploaded"), result.PhysicalPath);+ Assert.AreEqual("assets/images/uploaded", result.Path.Replace("\\", "/"));+ }++ [TestMethod]+ public void GetDirectoryInfo_MissingEverywhere_ReturnsNull()+ {+ //Act+ var result = _store.GetDirectoryInfo("assets/nothing");+ //Assert+ Assert.IsNull(result);+ Assert.IsFalse(Directory.Exists(Path.Combine(_media, "assets", "nothing")));+ }++ [TestMethod]+ public void GetDirectoryContent_MergesLayersWithPrimaryWinning()+ {+ //Arrange+ Directory.CreateDirectory(Path.Combine(_media, "assets", "custom"));+ File.WriteAllText(Path.Combine(_media, "assets", "custom", "style.css"), "edited");+ File.WriteAllText(Path.Combine(_media, "assets", "custom", "script.js"), "js");+ //Act+ var result = _store.GetDirectoryContent("assets/custom");+ //Assert+ Assert.HasCount(2, result);+ Assert.IsTrue(result.All(e => e.PhysicalPath.StartsWith(_media)));+ }++ [TestMethod]+ public async Task GetFileInfo_PathOutsideRoot_Throws()+ {+ //Act + Assert+ await Assert.ThrowsExactlyAsync<Exception>(() => _store.GetFileInfo("../outside.txt"));+ }+}diff --git a/src/Tests/Grand.Business.Storage.Tests/Services/MediaFileStoreFactoryTests.cs b/src/Tests/Grand.Business.Storage.Tests/Services/MediaFileStoreFactoryTests.csnew file mode 100644index 000000000..62bd417fd--- /dev/null+++ b/src/Tests/Grand.Business.Storage.Tests/Services/MediaFileStoreFactoryTests.cs@@ -0,0 +1,59 @@+using Grand.Business.Storage.Services;+using Microsoft.VisualStudio.TestTools.UnitTesting;++namespace Grand.Business.Storage.Tests.Services;++[TestClass]+public class MediaFileStoreFactoryTests+{+ private string _root;+ private string _webRoot;++ [TestInitialize]+ public void Init()+ {+ _root = Path.Combine(Path.GetTempPath(), "mediafactory-" + Guid.NewGuid().ToString("N"));+ _webRoot = Path.Combine(_root, "wwwroot");+ Directory.CreateDirectory(Path.Combine(_webRoot, "tenant"));+ }++ [TestCleanup]+ public void Cleanup()+ {+ Directory.Delete(_root, true);+ }++ [TestMethod]+ public void Create_NoMediaPath_ReturnsPlainWebRootStore()+ {+ //Act+ var result = MediaFileStoreFactory.Create(_webRoot, null, null);+ //Assert+ Assert.IsInstanceOfType<FileSystemStore>(result);+ }++ [TestMethod]+ public async Task Create_WithMediaPathAndDirectory_WritesUnderMediaDirectory()+ {+ //Arrange+ var media = Path.Combine(_root, "media");+ Directory.CreateDirectory(Path.Combine(media, "tenant"));+ var store = MediaFileStoreFactory.Create(_webRoot, media, "tenant");+ //Act+ await store.WriteAllText("sitemap.xml", "<urlset/>");+ //Assert+ Assert.IsTrue(File.Exists(Path.Combine(media, "tenant", "sitemap.xml")));+ Assert.IsFalse(File.Exists(Path.Combine(_webRoot, "tenant", "sitemap.xml")));+ }++ [TestMethod]+ public void Create_WithMediaPath_DoesNotTouchTheFileSystem()+ {+ //Arrange - resolved once per request scope; the media directory is created at startup instead+ var media = Path.Combine(_root, "media");+ //Act+ MediaFileStoreFactory.Create(_webRoot, media, "tenant");+ //Assert+ Assert.IsFalse(Directory.Exists(media));+ }+}diff --git a/src/Tests/Grand.Business.Storage.Tests/Services/PictureServiceMediaPathTests.cs b/src/Tests/Grand.Business.Storage.Tests/Services/PictureServiceMediaPathTests.csnew file mode 100644index 000000000..9414f014d--- /dev/null+++ b/src/Tests/Grand.Business.Storage.Tests/Services/PictureServiceMediaPathTests.cs@@ -0,0 +1,89 @@+using Grand.Business.Storage.Services;+using Grand.Data;+using Grand.Domain.Media;+using Grand.Infrastructure.Caching;+using Grand.Mediator;+using Microsoft.Extensions.Logging;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;++namespace Grand.Business.Storage.Tests.Services;++[TestClass]+public class PictureServiceMediaPathTests+{+ private string _media;+ private string _root;+ private PictureService _service;+ private string _webRoot;++ [TestInitialize]+ public void Init()+ {+ _root = Path.Combine(Path.GetTempPath(), "picture-media-" + Guid.NewGuid().ToString("N"));+ _media = Path.Combine(_root, "media");+ _webRoot = Path.Combine(_root, "wwwroot");+ Directory.CreateDirectory(Path.Combine(_webRoot, "assets", "images"));++ var store = new DefaultMediaFileStore(MediaFileStoreFactory.Create(_webRoot, _media, null));+ _service = new PictureService(new Mock<IRepository<Picture>>().Object,+ new Mock<ILogger<PictureService>>().Object, new Mock<IMediator>().Object, new Mock<ICacheBase>().Object,+ store, new MediaSettings(), new StorageSettings());+ }++ [TestCleanup]+ public void Cleanup()+ {+ foreach (var file in Directory.GetFiles(_root, "*", SearchOption.AllDirectories))+ File.SetAttributes(file, FileAttributes.Normal);+ Directory.Delete(_root, true);+ }++ [TestMethod]+ public async Task DeletePictureOnFileSystem_OriginalOnlyInReadOnlyWebRoot_LeavesItAndDoesNotThrow()+ {+ //Arrange - wwwroot is read-only in the container (readOnlyRootFilesystem)+ var shipped = Path.Combine(_webRoot, "assets", "images", "p1_0.jpeg");+ File.WriteAllText(shipped, "jpg");+ File.SetAttributes(shipped, FileAttributes.ReadOnly);+ //Act+ await _service.DeletePictureOnFileSystem(new Picture { Id = "p1", MimeType = "image/jpeg" });+ //Assert+ Assert.IsTrue(File.Exists(shipped));+ }++ [TestMethod]+ [Timeout(30_000)]+ public async Task GetPictureUrl_ThumbWrittenAsynchronously_SavesThumbOnVolume()+ {+ //Arrange - a large original makes the thumb write complete asynchronously, resuming on another thread,+ //while parallel requests generate the same thumb; a thread-affine lock (Mutex) used to hang them here+ var service = new PictureService(new Mock<IRepository<Picture>>().Object,+ new Mock<ILogger<PictureService>>().Object, new Mock<IMediator>().Object, new Mock<ICacheBase>().Object,+ new DefaultMediaFileStore(MediaFileStoreFactory.Create(_webRoot, _media, null)), new MediaSettings(),+ new StorageSettings { PictureStoreInDb = false });+ Directory.CreateDirectory(Path.Combine(_media, "assets", "images"));+ await File.WriteAllBytesAsync(Path.Combine(_media, "assets", "images", "p1_0.jpeg"), new byte[8 * 1024 * 1024]);++ //Act+ var urls = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => Task.Run(() =>+ service.GetPictureUrl(new Picture { Id = "p1", MimeType = "image/jpeg" }, 0, true, "http://localhost/"))));++ //Assert+ Assert.IsTrue(File.Exists(Path.Combine(_media, "assets", "images", "thumbs", "p1.jpeg")));+ Assert.AreEqual("http://localhost/assets/images/thumbs/p1.jpeg", urls[0]);+ }++ [TestMethod]+ public async Task DeletePictureOnFileSystem_OriginalOnVolume_IsDeleted()+ {+ //Arrange+ Directory.CreateDirectory(Path.Combine(_media, "assets", "images"));+ var onVolume = Path.Combine(_media, "assets", "images", "p1_0.jpeg");+ File.WriteAllText(onVolume, "jpg");+ //Act+ await _service.DeletePictureOnFileSystem(new Picture { Id = "p1", MimeType = "image/jpeg" });+ //Assert+ Assert.IsFalse(File.Exists(onVolume));+ }+}diff --git a/src/Tests/Grand.Infrastructure.Tests/Configuration/AppConfigExtensionsTests.cs b/src/Tests/Grand.Infrastructure.Tests/Configuration/AppConfigExtensionsTests.csnew file mode 100644index 000000000..124022edc--- /dev/null+++ b/src/Tests/Grand.Infrastructure.Tests/Configuration/AppConfigExtensionsTests.cs@@ -0,0 +1,80 @@+using Grand.Infrastructure.Configuration;+using Microsoft.VisualStudio.TestTools.UnitTesting;++namespace Grand.Infrastructure.Tests.Configuration;++[TestClass]+public class AppConfigExtensionsTests+{+ private static readonly string ContentRoot = Path.Combine(Path.GetTempPath(), "grand-content-root");++ [TestMethod]+ [DataRow(null)]+ [DataRow("")]+ [DataRow(" ")]+ public void GetMediaRootPath_NotConfigured_ReturnsNull(string mediaPath)+ {+ //Arrange+ var config = new AppConfig { MediaPath = mediaPath };+ //Act+ var result = config.GetMediaRootPath(ContentRoot);+ //Assert+ Assert.IsNull(result);+ }++ [TestMethod]+ public void GetMediaRootPath_RelativePath_ResolvesAgainstContentRoot()+ {+ //Arrange+ var config = new AppConfig { MediaPath = "media" };+ //Act+ var result = config.GetMediaRootPath(ContentRoot);+ //Assert+ Assert.AreEqual(Path.Combine(ContentRoot, "media"), result);+ }++ [TestMethod]+ [DataRow(".")]+ [DataRow("..")]+ [DataRow("App_Data")]+ [DataRow("app_data/")]+ public void GetMediaRootPath_PathThatWouldPublishApplicationFiles_Throws(string mediaPath)+ {+ //Arrange - the media root is served at "/", so it must not expose appsettings.json or Settings.cfg+ var config = new AppConfig { MediaPath = mediaPath };+ //Act + Assert+ Assert.ThrowsExactly<InvalidOperationException>(() => config.GetMediaRootPath(ContentRoot));+ }++ [TestMethod]+ public void GetMediaRootPath_FileSystemRoot_Throws()+ {+ //Arrange - a root keeps its trailing separator, which must not be doubled into a non-matching prefix+ var config = new AppConfig { MediaPath = Path.GetPathRoot(ContentRoot) };+ //Act + Assert+ Assert.ThrowsExactly<InvalidOperationException>(() => config.GetMediaRootPath(ContentRoot));+ }++ [TestMethod]+ public void GetMediaRootPath_SubdirectoryOfAppData_Allowed()+ {+ //Arrange - a media folder inside a shared App_Data volume serves only that folder+ var config = new AppConfig { MediaPath = Path.Combine("App_Data", "media") };+ //Act+ var result = config.GetMediaRootPath(ContentRoot);+ //Assert+ Assert.AreEqual(Path.Combine(ContentRoot, "App_Data", "media"), result);+ }++ [TestMethod]+ public void GetMediaRootPath_AbsolutePath_ReturnedAsIs()+ {+ //Arrange+ var absolute = Path.Combine(Path.GetTempPath(), "shared-media");+ var config = new AppConfig { MediaPath = absolute };+ //Act+ var result = config.GetMediaRootPath(ContentRoot);+ //Assert+ Assert.AreEqual(absolute, result);+ }+}diff --git a/src/Tests/Grand.Web.Common.Tests/Infrastructure/MediaRootFileProviderTests.cs b/src/Tests/Grand.Web.Common.Tests/Infrastructure/MediaRootFileProviderTests.csnew file mode 100644index 000000000..84458d09a--- /dev/null+++ b/src/Tests/Grand.Web.Common.Tests/Infrastructure/MediaRootFileProviderTests.cs@@ -0,0 +1,131 @@+using Grand.Web.Common.Infrastructure;+using Microsoft.AspNetCore.Hosting;+using Microsoft.Extensions.FileProviders;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;++namespace Grand.Web.Common.Tests.Infrastructure;++[TestClass]+public class MediaRootFileProviderTests+{+ private Mock<IWebHostEnvironment> _env;+ private string _media;+ private string _root;+ private string _webRoot;++ [TestInitialize]+ public void Init()+ {+ _root = Path.Combine(Path.GetTempPath(), "mediaroot-" + Guid.NewGuid().ToString("N"));+ _webRoot = Path.Combine(_root, "wwwroot");+ _media = Path.Combine(_root, "media");+ Directory.CreateDirectory(Path.Combine(_webRoot, "assets", "custom"));+ File.WriteAllText(Path.Combine(_webRoot, "assets", "custom", "style.css"), "shipped");+ File.WriteAllText(Path.Combine(_webRoot, "favicon.ico"), "ico");++ _env = new Mock<IWebHostEnvironment>();+ _env.SetupProperty(e => e.WebRootFileProvider, new PhysicalFileProvider(_webRoot));+ }++ [TestCleanup]+ public void Cleanup()+ {+ Directory.Delete(_root, true);+ }++ private static string Read(IFileProvider provider, string path)+ {+ using var reader = new StreamReader(provider.GetFileInfo(path).CreateReadStream());+ return reader.ReadToEnd();+ }++ [TestMethod]+ public void Apply_NoMediaPath_LeavesProviderUntouched()+ {+ //Arrange+ var original = _env.Object.WebRootFileProvider;+ //Act+ MediaRootFileProvider.Apply(_env.Object, null, null);+ //Assert+ Assert.AreSame(original, _env.Object.WebRootFileProvider);+ }++ [TestMethod]+ public void Apply_MissingMediaDirectory_IsCreated()+ {+ //Act+ MediaRootFileProvider.Apply(_env.Object, _media, null);+ //Assert+ Assert.IsTrue(Directory.Exists(_media));+ }++ [TestMethod]+ public void Apply_FileInBoth_MediaWins()+ {+ //Arrange+ Directory.CreateDirectory(Path.Combine(_media, "assets", "custom"));+ File.WriteAllText(Path.Combine(_media, "assets", "custom", "style.css"), "edited");+ //Act+ MediaRootFileProvider.Apply(_env.Object, _media, null);+ //Assert+ Assert.AreEqual("edited", Read(_env.Object.WebRootFileProvider, "assets/custom/style.css"));+ }++ [TestMethod]+ public void Apply_FileOnlyInWebRoot_StillServed()+ {+ //Act+ MediaRootFileProvider.Apply(_env.Object, _media, null);+ //Assert+ Assert.AreEqual("ico", Read(_env.Object.WebRootFileProvider, "favicon.ico"));+ }++ [TestMethod]+ public void Apply_SitemapOnlyInMedia_ServedAtRoot()+ {+ //Arrange+ Directory.CreateDirectory(_media);+ File.WriteAllText(Path.Combine(_media, "sitemap.xml"), "<urlset/>");+ //Act+ MediaRootFileProvider.Apply(_env.Object, _media, null);+ //Assert+ Assert.AreEqual("<urlset/>", Read(_env.Object.WebRootFileProvider, "sitemap.xml"));+ }++ [TestMethod]+ public void Apply_WithDirectory_CreatesMediaDirectory()+ {+ //Act+ MediaRootFileProvider.Apply(_env.Object, _media, "tenant");+ //Assert+ Assert.IsTrue(Directory.Exists(Path.Combine(_media, "tenant")));+ }++ [TestMethod]+ [DataRow(null, "assets/images/thumbs/p1_100.jpg")]+ [DataRow("tenant", "tenant/assets/images/thumbs/p1_100.jpg")]+ public void Apply_ThumbOnlyInWebRoot_NotServed(string directory, string thumbPath)+ {+ //Arrange - a thumb left in wwwroot from before the switch; the picture may have been deleted since+ var physical = Path.Combine(_webRoot, thumbPath.Replace('/', Path.DirectorySeparatorChar));+ Directory.CreateDirectory(Path.GetDirectoryName(physical)!);+ File.WriteAllText(physical, "stale");+ //Act+ MediaRootFileProvider.Apply(_env.Object, _media, directory);+ //Assert+ Assert.IsFalse(_env.Object.WebRootFileProvider.GetFileInfo("/" + thumbPath).Exists);+ }++ [TestMethod]+ public void Apply_ThumbOnVolume_Served()+ {+ //Arrange+ Directory.CreateDirectory(Path.Combine(_media, "assets", "images", "thumbs"));+ File.WriteAllText(Path.Combine(_media, "assets", "images", "thumbs", "p1_100.jpg"), "fresh");+ //Act+ MediaRootFileProvider.Apply(_env.Object, _media, null);+ //Assert+ Assert.AreEqual("fresh", Read(_env.Object.WebRootFileProvider, "/assets/images/thumbs/p1_100.jpg"));+ }+}diff --git a/src/Web/Grand.Web.Admin/Controllers/SettingController.cs b/src/Web/Grand.Web.Admin/Controllers/SettingController.csindex 1fcaf63df..775218bef 100644--- a/src/Web/Grand.Web.Admin/Controllers/SettingController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/SettingController.cs@@ -746,7 +746,8 @@ public class SettingController(}[HttpPost]- public async Task<IActionResult> PushNotifications(PushNotificationsSettingsModel model, [FromServices] IConfiguration configuration, [FromServices] IWebHostEnvironment webHostEnvironment)+ public async Task<IActionResult> PushNotifications(PushNotificationsSettingsModel model,+ [FromServices] IMediaFileStore mediaFileStore){var storeScope = await GetActiveStore();var settings = await settingService.LoadSetting<PushNotificationsSettings>(storeScope);@@ -758,42 +759,23 @@ public class SettingController(await ClearCache();//save to file- SavePushNotificationsToFile(model);+ await SavePushNotificationsToFile(model);Success(translationService.GetResource("Admin.Configuration.Updated"));return await PushNotifications();- void SavePushNotificationsToFile(PushNotificationsSettingsModel model)+ async Task SavePushNotificationsToFile(PushNotificationsSettingsModel model){- var fullPath = GetSafeFilePath(configuration, webHostEnvironment, "firebase-messaging-sw.js");+ const string fileName = "firebase-messaging-sw.js";- if (System.IO.File.Exists(fullPath))- {- var lines = System.IO.File.ReadAllLines(fullPath);- lines = UpdateFileLines(lines, model);- System.IO.File.WriteAllLines(fullPath, lines);- }- else- throw new ArgumentNullException($"{fullPath} not exist");- }- }-- private static string GetSafeFilePath(IConfiguration configuration, IWebHostEnvironment webHostEnvironment, string filename)- {- var directoryParam = configuration[CommonPath.DirectoryParam] ?? "";-- // Validate directoryParam to ensure it does not contain ".." or path separators- if (directoryParam.Contains("..") || directoryParam.Contains("/") || directoryParam.Contains("\\"))- throw new ArgumentException("Invalid directory parameter - contains illegal characters.");-- var safeDirectoryName = Path.GetFileName(directoryParam);- var combinedPath = Path.Combine(webHostEnvironment.WebRootPath, safeDirectoryName, filename);- var fullPath = Path.GetFullPath(combinedPath, webHostEnvironment.WebRootPath);+ //read from the media path, or the template shipped in wwwroot the first time+ if (await mediaFileStore.GetFileInfo(fileName) == null)+ throw new ArgumentNullException($"{fileName} not exist");- if (!fullPath.StartsWith(webHostEnvironment.WebRootPath, StringComparison.OrdinalIgnoreCase))- throw new ArgumentException("Invalid path parameter - attempt to go outside allowed directory.");-- return fullPath;+ var lines = (await mediaFileStore.ReadAllText(fileName)).Split(["\r\n", "\n"], StringSplitOptions.None);+ lines = UpdateFileLines(lines, model);+ await mediaFileStore.WriteAllText(fileName, string.Join(Environment.NewLine, lines));+ }}private static string[] UpdateFileLines(string[] lines, PushNotificationsSettingsModel model)diff --git a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.csindex 88ad025cb..24ed158e1 100644--- a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs+++ b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs@@ -154,6 +154,12 @@ public static class ApplicationBuilderExtensions/// <param name="appConfig">AppConfig</param>public static void UseGrandStaticFiles(this WebApplication application, AppConfig appConfig){+ var webHostEnvironment = application.Services.GetRequiredService<IWebHostEnvironment>();++ //files written at runtime (shared media path) take precedence over wwwroot+ MediaRootFileProvider.Apply(webHostEnvironment, appConfig.GetMediaRootPath(webHostEnvironment.ContentRootPath),+ application.Configuration[CommonPath.DirectoryParam]);+//static filesapplication.UseStaticFiles(new StaticFileOptions {OnPrepareResponse = ctx =>@@ -162,7 +168,6 @@ public static class ApplicationBuilderExtensionsctx.Context.Response.Headers.Append(HeaderNames.CacheControl, appConfig.StaticFilesCacheControl);}});- var webHostEnvironment = application.Services.GetRequiredService<IWebHostEnvironment>();var pluginsPath = Path.Combine(webHostEnvironment.ContentRootPath, CommonPath.Plugins);//pluginsdiff --git a/src/Web/Grand.Web.Common/Infrastructure/MediaRootFileProvider.cs b/src/Web/Grand.Web.Common/Infrastructure/MediaRootFileProvider.csnew file mode 100644index 000000000..650958edd--- /dev/null+++ b/src/Web/Grand.Web.Common/Infrastructure/MediaRootFileProvider.cs@@ -0,0 +1,56 @@+using Grand.Business.Storage.Services;+using Microsoft.AspNetCore.Hosting;+using Microsoft.Extensions.FileProviders;+using Microsoft.Extensions.Primitives;++namespace Grand.Web.Common.Infrastructure;++public static class MediaRootFileProvider+{+ /// <summary>+ /// Serves files from the media path ahead of wwwroot, so a file written at runtime replaces the copy+ /// that shipped with the build, and every instance sharing the volume serves the same file+ /// </summary>+ /// <param name="webHostEnvironment">Host environment whose WebRootFileProvider is layered</param>+ /// <param name="mediaRootPath">Media physical path; null or empty leaves wwwroot alone</param>+ /// <param name="directory">Optional per-installation subdirectory (the "Directory" config value)</param>+ public static void Apply(IWebHostEnvironment webHostEnvironment, string mediaRootPath, string directory)+ {+ if (string.IsNullOrEmpty(mediaRootPath)) return;++ //created once here, so the per-request media file store never has to+ Directory.CreateDirectory(Path.Combine(mediaRootPath, directory ?? ""));++ //thumbs never come from wwwroot, as in the media file store: a stale copy would outlive a deleted picture+ var hiddenPaths = MediaFileStoreFactory.PrimaryOnlyPaths+ .Select(p => string.IsNullOrEmpty(directory) ? p : $"{directory.Trim('/', '\\')}/{p}")+ .ToArray();++ webHostEnvironment.WebRootFileProvider = new CompositeFileProvider(+ new PhysicalFileProvider(mediaRootPath),+ new HidingFileProvider(webHostEnvironment.WebRootFileProvider, hiddenPaths));+ }++ private sealed class HidingFileProvider(IFileProvider inner, string[] hiddenPaths) : IFileProvider+ {+ public IFileInfo GetFileInfo(string subpath)+ {+ return IsHidden(subpath) ? new NotFoundFileInfo(subpath) : inner.GetFileInfo(subpath);+ }++ public IDirectoryContents GetDirectoryContents(string subpath)+ {+ return IsHidden(subpath) ? NotFoundDirectoryContents.Singleton : inner.GetDirectoryContents(subpath);+ }++ public IChangeToken Watch(string filter) => inner.Watch(filter);++ private bool IsHidden(string subpath)+ {+ var path = (subpath ?? "").Replace('\\', '/').Trim('/');+ return hiddenPaths.Any(p =>+ path.Equals(p, StringComparison.OrdinalIgnoreCase) ||+ path.StartsWith(p + "/", StringComparison.OrdinalIgnoreCase));+ }+ }+}diff --git a/src/Web/Grand.Web/App_Data/appsettings.json b/src/Web/Grand.Web/App_Data/appsettings.jsonindex cb8b0e50a..979044712 100644--- a/src/Web/Grand.Web/App_Data/appsettings.json+++ b/src/Web/Grand.Web/App_Data/appsettings.json@@ -4,6 +4,10 @@"DisplayFullErrorStack": false,//Value of "Cache-Control" header value for static content"StaticFilesCacheControl": "public,max-age=31536000",+ //Directory for files written at runtime: custom css/js, uploaded images, thumbnails, sitemap*.xml,+ //firebase-messaging-sw.js. Empty keeps them in wwwroot. When running more than one instance (pods),+ //set it to a shared volume mounted on every instance. A relative path is resolved against the application directory.+ "MediaPath": "",//Enable the session-based TempData provider"UseSessionStateTempDataProvider": false,//A value indicating whether SEO friendly URLs with multiple languages are enabled