From 9a8a669dd9408c5bf90d7ad45f28b31114b51728 Mon Sep 17 00:00:00 2001 From: "mark.hall@perficient.com" Date: Tue, 7 Jan 2025 19:42:38 -0300 Subject: [PATCH] Fixes #895 Update settings service. --- .../Infrastructure/Cms/Initialize.cs | 2 + .../Cms/Settings/ISettingsService.cs | 14 + .../Cms/Settings/SettingEventData.cs | 18 + .../Cms/Settings/SettingsService.cs | 593 +++++++++--------- .../Infrastructure/ContentInstaller.cs | 10 - 5 files changed, 327 insertions(+), 310 deletions(-) create mode 100644 src/Foundation/Infrastructure/Cms/Settings/ISettingsService.cs create mode 100644 src/Foundation/Infrastructure/Cms/Settings/SettingEventData.cs diff --git a/src/Foundation/Infrastructure/Cms/Initialize.cs b/src/Foundation/Infrastructure/Cms/Initialize.cs index 5097bd0f..a2dcd0f0 100644 --- a/src/Foundation/Infrastructure/Cms/Initialize.cs +++ b/src/Foundation/Infrastructure/Cms/Initialize.cs @@ -23,10 +23,12 @@ void IConfigurableModule.ConfigureContainer(ServiceConfigurationContext context) void IInitializableModule.Initialize(InitializationEngine context) { + context.Locate.Advanced.GetInstance().InitializeSettings(); } void IInitializableModule.Uninitialize(InitializationEngine context) { + } } } \ No newline at end of file diff --git a/src/Foundation/Infrastructure/Cms/Settings/ISettingsService.cs b/src/Foundation/Infrastructure/Cms/Settings/ISettingsService.cs new file mode 100644 index 00000000..3dfa19da --- /dev/null +++ b/src/Foundation/Infrastructure/Cms/Settings/ISettingsService.cs @@ -0,0 +1,14 @@ +using System.Collections.Concurrent; + +namespace Foundation.Infrastructure.Cms.Settings; + +public interface ISettingsService +{ + ContentReference GlobalSettingsRoot { get; set; } + ConcurrentDictionary> SiteSettings { get; } + T GetSiteSettings(Guid? siteId = null, string language = null) where T : SettingsBase; + void InitializeSettings(); + void RegisterContentRoots(); + void UpdateSettings(Guid siteId, IContent content); + void UpdateSettings(); +} diff --git a/src/Foundation/Infrastructure/Cms/Settings/SettingEventData.cs b/src/Foundation/Infrastructure/Cms/Settings/SettingEventData.cs new file mode 100644 index 00000000..1b732c8b --- /dev/null +++ b/src/Foundation/Infrastructure/Cms/Settings/SettingEventData.cs @@ -0,0 +1,18 @@ +using EPiServer.Events; +using System.Runtime.Serialization; + +namespace Foundation.Infrastructure.Cms.Settings; + +[DataContract] +[EventsServiceKnownType] +public class SettingEventData +{ + [DataMember] + public string SiteId { get; set; } + + [DataMember] + public string ContentId { get; set; } + + [DataMember] + public string Language { get; set; } +} diff --git a/src/Foundation/Infrastructure/Cms/Settings/SettingsService.cs b/src/Foundation/Infrastructure/Cms/Settings/SettingsService.cs index 9eada9f0..cb780751 100644 --- a/src/Foundation/Infrastructure/Cms/Settings/SettingsService.cs +++ b/src/Foundation/Infrastructure/Cms/Settings/SettingsService.cs @@ -1,403 +1,396 @@ -using EPiServer.DataAccess; +using System.Collections.Concurrent; +using System.Globalization; +using EPiServer.DataAccess; +using EPiServer.Events; +using EPiServer.Events.Clients; using EPiServer.Framework.TypeScanner; -using EPiServer.Globalization; -using EPiServer.Logging; using EPiServer.Security; -using System.Collections.Concurrent; +using Microsoft.Extensions.Logging; -namespace Foundation.Infrastructure.Cms.Settings +namespace Foundation.Infrastructure.Cms.Settings; +public class SettingsService : ISettingsService, IDisposable { - public interface ISettingsService + //Generate unique id for your event and the raiser + private readonly Guid _raiserId; + private static Guid EventId => new("b29b8aef-2a17-4432-ad16-8cd6cc6953e3"); + + private readonly IContentRepository _contentRepository; + private readonly ContentRootService _contentRootService; + private readonly IContentTypeRepository _contentTypeRepository; + private readonly ILogger _log; + private readonly ITypeScannerLookup _typeScannerLookup; + private readonly IContentEvents _contentEvents; + private readonly ISiteDefinitionEvents _siteDefinitionEvents; + private readonly ISiteDefinitionRepository _siteDefinitionRepository; + private readonly ISiteDefinitionResolver _siteDefinitionResolver; + private readonly IHttpContextAccessor _httpContext; + private readonly IEventRegistry _eventRegistry; + private readonly IContentLanguageAccessor _contentLanguageAccessor; + + public SettingsService( + IContentRepository contentRepository, + ContentRootService contentRootService, + ITypeScannerLookup typeScannerLookup, + IContentTypeRepository contentTypeRepository, + IContentEvents contentEvents, + ISiteDefinitionEvents siteDefinitionEvents, + ISiteDefinitionRepository siteDefinitionRepository, + ISiteDefinitionResolver siteDefinitionResolver, + IHttpContextAccessor httpContext, + IEventRegistry eventRegistry, + IContentLanguageAccessor contentLanguageAccessor, + ILogger logger) { - ContentReference GlobalSettingsRoot { get; set; } - ConcurrentDictionary> SiteSettings { get; } - T GetSiteSettings(Guid? siteId = null); - void InitializeSettings(); - void UnintializeSettings(); - void UpdateSettings(Guid siteId, IContent content, bool isContentNotPublished); - void UpdateSettings(); + _contentRepository = contentRepository; + _contentRootService = contentRootService; + _typeScannerLookup = typeScannerLookup; + _contentTypeRepository = contentTypeRepository; + _contentEvents = contentEvents; + _siteDefinitionEvents = siteDefinitionEvents; + _siteDefinitionRepository = siteDefinitionRepository; + _siteDefinitionResolver = siteDefinitionResolver; + _httpContext = httpContext; + _eventRegistry = eventRegistry; + _raiserId = Guid.NewGuid(); + _contentLanguageAccessor = contentLanguageAccessor; + _log = logger; } - public static class ISettingsServiceExtensions + public ConcurrentDictionary> SiteSettings { get; } = new ConcurrentDictionary>(); + + public ContentReference GlobalSettingsRoot { get; set; } + + public List GetAllSiteSettings() where T : SettingsBase { - public static T GetSiteSettingsOrThrow(this ISettingsService settingsService, - Func shouldThrow, - string message) where T : SettingsBase + var sites = _siteDefinitionRepository.List(); + var siteSettings = new List(); + + foreach (var site in sites) { - var settings = settingsService.GetSiteSettings(); - if (settings == null || (shouldThrow?.Invoke(settings) ?? false)) + var settings = GetSiteSettings(site.Id); + if (settings != null) { - throw new InvalidOperationException(message); + siteSettings.Add(settings); } + } + + return siteSettings; + } - return settings; + public T GetSiteSettings(Guid? siteId = null, string language = null) where T : SettingsBase + { + if (!siteId.HasValue) + { + siteId = ResolveSiteId(); + if (siteId == Guid.Empty) + { + return default; + } } - public static bool TryGetSiteSettings(this ISettingsService settingsService, out T value) where T : SettingsBase + try + { + if (SiteSettings.TryGetValue(siteId.Value, out var siteSettings) && + siteSettings.TryGetValue(typeof(T), out var settingId)) + { + return _contentRepository.Get(settingId, language == null ? _contentLanguageAccessor.Language : CultureInfo.GetCultureInfo(language)); + } + } + catch (KeyNotFoundException keyNotFoundException) + { + _log.LogError(keyNotFoundException, $"[Settings] {keyNotFoundException.Message}"); + } + catch (ArgumentNullException argumentNullException) { - value = settingsService.GetSiteSettings(); - return value != null; + _log.LogError(argumentNullException, $"[Settings] {argumentNullException.Message}"); } + + return default; } - public class SettingsService : ISettingsService + public void InitializeSettings() { - public const string GlobalSettingsRootName = "Global Settings Root"; - private readonly IContentRepository _contentRepository; - private readonly IContentVersionRepository _contentVersionRepository; - private readonly ContentRootService _contentRootService; - private readonly IContentTypeRepository _contentTypeRepository; - private readonly ILogger _log = LogManager.GetLogger(); - private readonly ITypeScannerLookup _typeScannerLookup; - private readonly IContentEvents _contentEvents; - private readonly ISiteDefinitionEvents _siteDefinitionEvents; - private readonly ISiteDefinitionRepository _siteDefinitionRepository; - private readonly ISiteDefinitionResolver _siteDefinitionResolver; - private readonly IHttpContextAccessor _httpContextAccessor; - private readonly IContextModeResolver _contextModeResolver; - - public SettingsService( - IContentRepository contentRepository, - IContentVersionRepository contentVersionRepository, - ContentRootService contentRootService, - ITypeScannerLookup typeScannerLookup, - IContentTypeRepository contentTypeRepository, - IContentEvents contentEvents, - ISiteDefinitionEvents siteDefinitionEvents, - ISiteDefinitionRepository siteDefinitionRepository, - ISiteDefinitionResolver siteDefinitionResolver, - IHttpContextAccessor httpContextAccessor, - IContextModeResolver contextModeResolver) + try { - _contentRepository = contentRepository; - _contentVersionRepository = contentVersionRepository; - _contentRootService = contentRootService; - _typeScannerLookup = typeScannerLookup; - _contentTypeRepository = contentTypeRepository; - _contentEvents = contentEvents; - _siteDefinitionEvents = siteDefinitionEvents; - _siteDefinitionRepository = siteDefinitionRepository; - _siteDefinitionResolver = siteDefinitionResolver; - _httpContextAccessor = httpContextAccessor; - _contextModeResolver = contextModeResolver; + RegisterContentRoots(); } + catch (NotSupportedException notSupportedException) + { + _log.LogError(notSupportedException, $"[Settings] {notSupportedException.Message}"); + throw; + } + catch (InvalidOperationException ex) + { + _log.LogError(ex, ex.Message); + } + _contentEvents.PublishedContent += PublishedContent; + _siteDefinitionEvents.SiteCreated += SiteCreated; + _siteDefinitionEvents.SiteUpdated += SiteUpdated; + _siteDefinitionEvents.SiteDeleted += SiteDeleted; - public ConcurrentDictionary> SiteSettings { get; } = new ConcurrentDictionary>(); - - public ContentReference GlobalSettingsRoot { get; set; } + var settingsEvent = _eventRegistry.Get(EventId); + settingsEvent.Raised += SettingsEvent_Raised; + } - public T GetSiteSettings(Guid? siteId = null) + public void UpdateSettings(Guid siteId, IContent content) + { + var contentType = content.GetOriginalType(); + try { - var contentLanguage = ContentLanguage.PreferredCulture.Name; - if (!siteId.HasValue) + if (!SiteSettings.ContainsKey(siteId)) { - siteId = ResolveSiteId(); - if (siteId == Guid.Empty) - { - return default; - } - } - try - { - if (_contextModeResolver.CurrentMode == ContextMode.Edit) - { - if (SiteSettings.TryGetValue(siteId.Value.ToString() + $"-common-draft-{contentLanguage}", out var siteSettings)) - { - if (siteSettings.TryGetValue(typeof(T), out var setting)) - { - return (T)setting; - } - } - if (SiteSettings.TryGetValue(siteId.Value.ToString() + "-common-draft-default", out var defaultSiteSettings)) - { - if (defaultSiteSettings.TryGetValue(typeof(T), out var defaultSetting)) - { - return (T)defaultSetting; - } - } - } - else - { - if (SiteSettings.TryGetValue(siteId.Value.ToString() + $"-{contentLanguage}", out var siteSettings) && siteSettings.TryGetValue(typeof(T), out var setting)) - { - return (T)setting; - } - if (SiteSettings.TryGetValue(siteId.Value.ToString() + "-default", out var defaultSiteSettings) && defaultSiteSettings.TryGetValue(typeof(T), out var defaultSetting)) - { - return (T)defaultSetting; - } - } - } - catch (KeyNotFoundException keyNotFoundException) - { - _log.Error($"[Settings] {keyNotFoundException.Message}", exception: keyNotFoundException); - } - catch (ArgumentNullException argumentNullException) - { - _log.Error($"[Settings] {argumentNullException.Message}", exception: argumentNullException); + SiteSettings[siteId] = new Dictionary(); } - return default; + SiteSettings[siteId][contentType] = content.ContentGuid; + } + catch (KeyNotFoundException keyNotFoundException) + { + _log.LogError(keyNotFoundException, $"[Settings] {keyNotFoundException.Message}"); + } + catch (ArgumentNullException argumentNullException) + { + _log.LogError(argumentNullException, $"[Settings] {argumentNullException.Message}"); + } + } + + public void UpdateSettings() + { + var root = _contentRepository.GetItems(_contentRootService.List(), new LoaderOptions()) + .FirstOrDefault(x => x.ContentGuid == SettingsFolder.SettingsRootGuid); + + if (root == null) + { + return; } - public void UpdateSettings(Guid siteId, IContent content, bool isContentNotPublished) + GlobalSettingsRoot = root.ContentLink; + var children = _contentRepository.GetChildren(GlobalSettingsRoot).ToList(); + foreach (var site in _siteDefinitionRepository.List()) { - var contentType = content.GetOriginalType(); - var contentLanguage = ContentLanguage.PreferredCulture.Name; - try + var folder = children.Find(x => x.Name.Equals(site.Name, StringComparison.InvariantCultureIgnoreCase)); + if (folder == null) { - if (isContentNotPublished) - { - if (!SiteSettings.ContainsKey(siteId.ToString() + $"-default")) - { - SiteSettings[$"{siteId}-common-draft-default"] = new Dictionary(); - } + CreateSiteFolder(site); + return; + } - if (!SiteSettings[$"{siteId}-common-draft-default"].ContainsKey(contentType)) - { - SiteSettings[$"{siteId}-common-draft-default"][contentType] = content; - } + var settingsModelTypes = _typeScannerLookup.AllTypes + .Where(t => t.GetCustomAttributes(typeof(SettingsContentTypeAttribute), false).Length > 0); - if (!SiteSettings.ContainsKey(siteId.ToString() + $"-{contentLanguage}")) - { - SiteSettings[$"{siteId}-common-draft-{contentLanguage}"] = new Dictionary(); - } + foreach (var settingsType in settingsModelTypes) + { + if (settingsType.GetCustomAttributes(typeof(SettingsContentTypeAttribute), false) + .FirstOrDefault() is not SettingsContentTypeAttribute attribute) + { + continue; + } + + var siteSetting = _contentRepository.GetChildren(folder.ContentLink, _contentLanguageAccessor.Language) + .FirstOrDefault(x => x.Name.Equals(attribute.SettingsName)); - SiteSettings[$"{siteId}-common-draft-{contentLanguage}"][contentType] = content; + if (siteSetting != null) + { + UpdateSettings(site.Id, siteSetting); } else { - if (!SiteSettings.ContainsKey(siteId.ToString() + $"-default")) - { - SiteSettings[siteId.ToString() + $"-default"] = new Dictionary(); - SiteSettings[$"{siteId}-common-draft-default"] = new Dictionary(); - } + var contentType = _contentTypeRepository.Load(settingsType); + var newSettings = _contentRepository.GetDefault(folder.ContentLink, contentType.ID); + newSettings.Name = attribute.SettingsName; - if (!SiteSettings[$"{siteId}-default"].ContainsKey(contentType)) + try { - SiteSettings[$"{siteId}-default"][contentType] = content; + _ = _contentRepository.Save(newSettings, SaveAction.Publish, AccessLevel.NoAccess); + UpdateSettings(site.Id, newSettings); } - - if (!SiteSettings[$"{siteId}-common-draft-default"].ContainsKey(contentType)) - { - SiteSettings[$"{siteId}-common-draft-default"][contentType] = content; - } - - if (!SiteSettings.ContainsKey(siteId.ToString() + $"-{contentLanguage}")) + catch (Exception e) { - SiteSettings[siteId.ToString() + $"-{contentLanguage}"] = new Dictionary(); - SiteSettings[$"{siteId}-common-draft-{contentLanguage}"] = new Dictionary(); + _log.LogError(e.Message); } - - SiteSettings[siteId.ToString() + $"-{contentLanguage}"][contentType] = content; - SiteSettings[$"{siteId}-common-draft-{contentLanguage}"][contentType] = content; } - } - catch (KeyNotFoundException keyNotFoundException) - { - _log.Error($"[Settings] {keyNotFoundException.Message}", exception: keyNotFoundException); - } - catch (ArgumentNullException argumentNullException) - { - _log.Error($"[Settings] {argumentNullException.Message}", exception: argumentNullException); + } } + } - public void InitializeSettings() - { - try - { - RegisterContentRoots(); - } - catch (NotSupportedException notSupportedException) - { - _log.Error($"[Settings] {notSupportedException.Message}", exception: notSupportedException); - throw; - } + public void RegisterContentRoots() + { + var registeredRoots = _contentRepository.GetItems(_contentRootService.List(), new LoaderOptions()); + var settingsRootRegistered = registeredRoots.Any(x => x.ContentGuid == SettingsFolder.SettingsRootGuid && x.Name.Equals(SettingsFolder.SettingsRootName)); - _contentEvents.PublishedContent += PublishedContent; - _contentEvents.SavedContent += SavedContent; - _siteDefinitionEvents.SiteCreated += SiteCreated; - _siteDefinitionEvents.SiteUpdated += SiteUpdated; - _siteDefinitionEvents.SiteDeleted += SiteDeleted; + if (!settingsRootRegistered) + { + _contentRootService.Register(SettingsFolder.SettingsRootName, SettingsFolder.SettingsRootGuid, ContentReference.RootPage); } - public void UnintializeSettings() + UpdateSettings(); + } + + public void Dispose() + { + if (_contentEvents != null) { _contentEvents.PublishedContent -= PublishedContent; - _contentEvents.SavedContent -= SavedContent; + } + + if (_siteDefinitionEvents != null) + { _siteDefinitionEvents.SiteCreated -= SiteCreated; _siteDefinitionEvents.SiteUpdated -= SiteUpdated; _siteDefinitionEvents.SiteDeleted -= SiteDeleted; } - public void UpdateSettings() + if (_eventRegistry != null) { - var root = _contentRepository.GetItems(_contentRootService.List(), new LoaderOptions()) - .FirstOrDefault(x => x.ContentGuid == SettingsFolder.SettingsRootGuid); - - if (root == null) - { - return; - } - - GlobalSettingsRoot = root.ContentLink; - var children = _contentRepository.GetChildren(GlobalSettingsRoot).ToList(); - foreach (var site in _siteDefinitionRepository.List()) - { - var folder = children.Find(x => x.Name.Equals(site.Name, StringComparison.InvariantCultureIgnoreCase)); - if (folder != null) - { - foreach (var child in _contentRepository.GetChildren(folder.ContentLink)) - { - UpdateSettings(site.Id, child, false); - - // add draft (not published version) settings - var darftContentLink = _contentVersionRepository.LoadCommonDraft(child.ContentLink, ContentLanguage.PreferredCulture.Name); - if (darftContentLink != null) - { - var settingsDraft = _contentRepository.Get(darftContentLink.ContentLink); - UpdateSettings(site.Id, settingsDraft, true); - } - } - continue; - } - CreateSiteFolder(site); - } + var settingsEvent = _eventRegistry.Get(EventId); + settingsEvent.Raised -= SettingsEvent_Raised; } - private void RegisterContentRoots() - { - var registeredRoots = _contentRepository.GetItems(_contentRootService.List(), new LoaderOptions()); - var settingsRootRegistered = registeredRoots.Any(x => x.ContentGuid == SettingsFolder.SettingsRootGuid && x.Name.Equals(SettingsFolder.SettingsRootName)); + GC.SuppressFinalize(this); + } - if (!settingsRootRegistered) - { - _contentRootService.Register(SettingsFolder.SettingsRootName, SettingsFolder.SettingsRootGuid, ContentReference.RootPage); - } + private void CreateSiteFolder(SiteDefinition siteDefinition) + { + var folder = _contentRepository.GetDefault(GlobalSettingsRoot); + folder.Name = siteDefinition.Name; + var reference = _contentRepository.Save(folder, SaveAction.Publish, AccessLevel.NoAccess); - UpdateSettings(); - } + var settingsModelTypes = _typeScannerLookup.AllTypes + .Where(t => t.GetCustomAttributes(typeof(SettingsContentTypeAttribute), false).Length > 0); - private void CreateSiteFolder(SiteDefinition siteDefinition) + foreach (var settingsType in settingsModelTypes) { - var folder = _contentRepository.GetDefault(GlobalSettingsRoot); - folder.Name = siteDefinition.Name; - var reference = _contentRepository.Save(folder, SaveAction.Publish, AccessLevel.NoAccess); + if (settingsType.GetCustomAttributes(typeof(SettingsContentTypeAttribute), false) + .FirstOrDefault() is not SettingsContentTypeAttribute attribute) + { + continue; + } - var settingsModelTypes = _typeScannerLookup.AllTypes - .Where(t => t.GetCustomAttributes(typeof(SettingsContentTypeAttribute), false).Length > 0); + var contentType = _contentTypeRepository.Load(settingsType); + var newSettings = _contentRepository.GetDefault(reference, contentType.ID); + newSettings.Name = attribute.SettingsName; - foreach (var settingsType in settingsModelTypes) + try { - if (!(settingsType.GetCustomAttributes(typeof(SettingsContentTypeAttribute), false) - .FirstOrDefault() is SettingsContentTypeAttribute attribute)) - { - continue; - } - - var contentType = _contentTypeRepository.Load(settingsType); - var newSettings = _contentRepository.GetDefault(reference, contentType.ID); - newSettings.Name = attribute.SettingsName; _contentRepository.Save(newSettings, SaveAction.Publish, AccessLevel.NoAccess); - UpdateSettings(siteDefinition.Id, newSettings, false); + UpdateSettings(siteDefinition.Id, newSettings); } - } - - private void SiteCreated(object sender, SiteDefinitionEventArgs e) - { - if (_contentRepository.GetChildren(GlobalSettingsRoot) - .Any(x => x.Name.Equals(e.Site.Name, StringComparison.InvariantCultureIgnoreCase))) + catch (Exception e) { - return; + _log.LogError(e.Message); } - - CreateSiteFolder(e.Site); } + } - private void SiteDeleted(object sender, SiteDefinitionEventArgs e) + private void SiteCreated(object sender, SiteDefinitionEventArgs e) + { + if (_contentRepository.GetChildren(GlobalSettingsRoot) + .Any(x => x.Name.Equals(e.Site.Name, StringComparison.InvariantCultureIgnoreCase))) { - var folder = _contentRepository.GetChildren(GlobalSettingsRoot) - .FirstOrDefault(x => x.Name.Equals(e.Site.Name, StringComparison.InvariantCultureIgnoreCase)); + return; + } - if (folder == null) - { - return; - } + CreateSiteFolder(e.Site); + } - _contentRepository.Delete(folder.ContentLink, true, AccessLevel.NoAccess); + private void SiteDeleted(object sender, SiteDefinitionEventArgs e) + { + var folder = _contentRepository.GetChildren(GlobalSettingsRoot) + .FirstOrDefault(x => x.Name.Equals(e.Site.Name, StringComparison.InvariantCultureIgnoreCase)); + + if (folder == null) + { + return; } - private void SiteUpdated(object sender, SiteDefinitionEventArgs e) + _contentRepository.Delete(folder.ContentLink, true, AccessLevel.NoAccess); + } + + private void SiteUpdated(object sender, SiteDefinitionEventArgs e) + { + if (e is SiteDefinitionUpdatedEventArgs updatedArgs) { - var updatedArgs = e as SiteDefinitionUpdatedEventArgs; var prevSite = updatedArgs.PreviousSite; var updatedSite = updatedArgs.Site; var settingsRoot = GlobalSettingsRoot; - var currentSettingsFolder = _contentRepository.GetChildren(settingsRoot).FirstOrDefault(x => x.Name.Equals(prevSite.Name, StringComparison.InvariantCultureIgnoreCase)) as ContentFolder; - if (currentSettingsFolder != null) + if (_contentRepository.GetChildren(settingsRoot) + .FirstOrDefault(x => x.Name.Equals(prevSite.Name, StringComparison.InvariantCultureIgnoreCase)) is ContentFolder currentSettingsFolder) { var cloneFolder = currentSettingsFolder.CreateWritableClone(); cloneFolder.Name = updatedSite.Name; _contentRepository.Save(cloneFolder); return; } - - CreateSiteFolder(e.Site); } - private void PublishedContent(object sender, ContentEventArgs e) + CreateSiteFolder(e.Site); + } + + private void PublishedContent(object sender, ContentEventArgs e) + { + if (e?.Content is not SettingsBase) { - if (e == null) - { - return; - } + return; + } - if (e.Content is SettingsBase) - { - var parent = _contentRepository.Get(e.Content.ParentLink); - var site = _siteDefinitionRepository.Get(parent.Name); + var parent = _contentRepository.Get(e.Content.ParentLink); + var site = _siteDefinitionRepository.Get(parent.Name); - var id = site?.Id; - if (id == null || id == Guid.Empty) - { - return; - } - UpdateSettings(id.Value, e.Content, false); - } + var id = site?.Id; + if (id == null || id == Guid.Empty) + { + return; } + UpdateSettings(id.Value, e.Content); + RaiseEvent(new SettingEventData + { + SiteId = id.ToString(), + ContentId = e.Content.ContentGuid.ToString() + }); + } - private void SavedContent(object sender, ContentEventArgs e) + private Guid ResolveSiteId() + { + var request = _httpContext.HttpContext?.Request; + if (request == null) { - if (e == null) - { - return; - } + return Guid.Empty; + } - if (e.Content is SettingsBase) - { - var id = ResolveSiteId(); - if (id == Guid.Empty) - { - return; - } - UpdateSettings(id, e.Content, true); - } + var site = _siteDefinitionResolver.GetByHostname(request.Host.Value, false, out _); + if (site != null) + { + return site.Id; } - private Guid ResolveSiteId() + site = _siteDefinitionRepository.List() + .FirstOrDefault(x => x.Hosts.Any(x => x.Url.Host.Equals(request.Host.Value, StringComparison.OrdinalIgnoreCase))); + + if (site != null) { - var request = _httpContextAccessor.HttpContext?.Request; - if (request == null) - { - return Guid.Empty; - } - var site = _siteDefinitionResolver.GetByHostname(request.Host.Host, true, out var hostname); - if (site == null) + return site.Id; + } + + return Guid.Empty; + } + + private void SettingsEvent_Raised(object sender, EventNotificationEventArgs e) + { + // don't process events locally raised + if (e.RaiserId != _raiserId && e.Param is SettingEventData settingUpdate && settingUpdate != null) + { + if (Guid.TryParse(settingUpdate.ContentId, out var contentId)) { - return Guid.Empty; + var content = _contentRepository.Get(contentId); + if (content != null && settingUpdate.SiteId != null) + { + UpdateSettings(Guid.Parse(settingUpdate.SiteId), content); + } } - return site.Id; } } -} \ No newline at end of file + + private void RaiseEvent(SettingEventData message) => _eventRegistry.Get(EventId).Raise(_raiserId, message); + +} diff --git a/src/Foundation/Infrastructure/ContentInstaller.cs b/src/Foundation/Infrastructure/ContentInstaller.cs index 9db4f3cb..0b5be2f3 100644 --- a/src/Foundation/Infrastructure/ContentInstaller.cs +++ b/src/Foundation/Infrastructure/ContentInstaller.cs @@ -17,16 +17,12 @@ namespace Foundation.Infrastructure { public class ContentInstaller : IBlockingFirstRequestInitializer { - private readonly UIUserProvider _uIUserProvider; - private readonly UIRoleProvider _uIRoleProvider; - private readonly UISignInManager _uISignInManager; private readonly ISiteDefinitionRepository _siteDefinitionRepository; private readonly ContentRootService _contentRootService; private readonly IContentRepository _contentRepository; private readonly IDataImporter _dataImporter; private readonly IScheduledJobExecutor _scheduledJobExecutor; private readonly IScheduledJobRepository _scheduledJobRepository; - private readonly ISettingsService _settingsService; private readonly ILanguageBranchRepository _languageBranchRepository; private readonly IWebHostEnvironment _webHostEnvironment; private readonly EventedIndexingSettings _eventedIndexingSettings; @@ -44,7 +40,6 @@ public ContentInstaller(UIUserProvider uIUserProvider, IDataImporter dataImporter, IScheduledJobExecutor scheduledJobExecutor, IScheduledJobRepository scheduledJobRepository, - ISettingsService settingsService, ILanguageBranchRepository languageBranchRepository, IWebHostEnvironment webHostEnvironment, EventedIndexingSettings eventedIndexingSettings, @@ -53,16 +48,12 @@ public ContentInstaller(UIUserProvider uIUserProvider, IndexBuilder indexBuilder, IPrincipalAccessor principalAccessor) { - _uIUserProvider = uIUserProvider; - _uISignInManager = uISignInManager; - _uIRoleProvider = uIRoleProvider; _siteDefinitionRepository = siteDefinitionRepository; _contentRootService = contentRootService; _contentRepository = contentRepository; _dataImporter = dataImporter; _scheduledJobExecutor = scheduledJobExecutor; _scheduledJobRepository = scheduledJobRepository; - _settingsService = settingsService; _languageBranchRepository = languageBranchRepository; _webHostEnvironment = webHostEnvironment; _eventedIndexingSettings = eventedIndexingSettings; @@ -77,7 +68,6 @@ public ContentInstaller(UIUserProvider uIUserProvider, public async Task InitializeAsync(HttpContext httpContext) { InstallDefaultContent(httpContext); - _settingsService.InitializeSettings(); await Task.CompletedTask; }