-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCombinedResourceManager.cs
210 lines (181 loc) · 9.8 KB
/
CombinedResourceManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
using Autofac.Features.Metadata;
using Orchard.ContentManagement; // For generic ContentManager methods
using Orchard.DisplayManagement.Descriptors;
using Orchard.DisplayManagement.Descriptors.ResourceBindingStrategy;
using Orchard.Environment.Extensions;
using Orchard.Exceptions;
using Orchard.Logging;
using Orchard.Mvc;
using Orchard.Settings;
using Orchard.Themes;
using Orchard.UI.Resources;
using Piedone.Combinator.Extensions;
using Piedone.Combinator.Models;
using Piedone.Combinator.Services;
using Piedone.HelpfulLibraries.Utilities;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
namespace Piedone.Combinator
{
/// <summary>
/// A derivation of the ResourceManager that combines multiple resource files into one, thus speeding up the website download
/// </summary>
[OrchardSuppressDependency("Orchard.UI.Resources.ResourceManager")]
[OrchardFeature("Piedone.Combinator")]
public class CombinedResourceManager : ResourceManager
{
private readonly ISiteService _siteService;
private readonly ICombinatorService _combinatorService;
private readonly IShapeTableLocator _shapeTableLocator;
private readonly IThemeManager _themeManager;
private readonly IHttpContextAccessor _httpContextAccessor;
public ILogger Logger { get; set; }
public CombinedResourceManager(
IEnumerable<Meta<IResourceManifestProvider>> resourceProviders,
ISiteService siteService,
ICombinatorService combinatorService,
IShapeTableLocator shapeTableLocator,
IThemeManager themeManager,
IHttpContextAccessor httpContextAccessor)
: base(resourceProviders)
{
_siteService = siteService;
_combinatorService = combinatorService;
_shapeTableLocator = shapeTableLocator;
_themeManager = themeManager;
_httpContextAccessor = httpContextAccessor;
Logger = NullLogger.Instance;
}
public override IList<ResourceRequiredContext> BuildRequiredResources(string stringResourceType)
{
// It's necessary to make a copy since making a change to the local variable also changes the private one.
var resources = new List<ResourceRequiredContext>(base.BuildRequiredResources(stringResourceType));
var settingsPart = _siteService.GetSiteSettings().As<CombinatorSettingsPart>();
if (resources.Count == 0
|| Orchard.UI.Admin.AdminFilter.IsApplied(_httpContextAccessor.Current().Request.RequestContext) && !settingsPart.EnableForAdmin) return resources;
var resourceType = ResourceTypeHelper.StringTypeToEnum(stringResourceType);
try
{
Uri resourceBaseUri = null;
if (!string.IsNullOrEmpty(settingsPart.ResourceBaseUrl)) resourceBaseUri = UriHelper.CreateUri(settingsPart.ResourceBaseUrl);
var settings = new CombinatorSettings
{
CombineCdnResources = settingsPart.CombineCdnResources,
ResourceBaseUri = resourceBaseUri,
EmbedCssImages = settingsPart.EmbedCssImages,
EmbeddedImagesMaxSizeKB = settingsPart.EmbeddedImagesMaxSizeKB,
GenerateImageSprites = settingsPart.GenerateImageSprites,
MinifyResources = settingsPart.MinifyResources,
EnableResourceSharing = settingsPart.EnableResourceSharing
};
if (!string.IsNullOrEmpty(settingsPart.CombinationExcludeRegex)) settings.CombinationExcludeFilter = new Regex(settingsPart.CombinationExcludeRegex);
if (!string.IsNullOrEmpty(settingsPart.RemoteStorageUrlRegex)) settings.RemoteStorageUrlPattern = new Regex(settingsPart.RemoteStorageUrlRegex);
if (!string.IsNullOrEmpty(settingsPart.EmbedCssImagesStylesheetExcludeRegex)) settings.EmbedCssImagesStylesheetExcludeFilter = new Regex(settingsPart.EmbedCssImagesStylesheetExcludeRegex);
if (!string.IsNullOrEmpty(settingsPart.MinificationExcludeRegex)) settings.MinificationExcludeFilter = new Regex(settingsPart.MinificationExcludeRegex);
if (!string.IsNullOrEmpty(settingsPart.ResourceSharingExcludeRegex)) settings.ResourceSharingExcludeFilter = new Regex(settingsPart.ResourceSharingExcludeRegex);
if (!string.IsNullOrEmpty(settingsPart.ResourceSetRegexes))
{
var setRegexes = new List<Regex>();
foreach (var regex in settingsPart.ResourceSetRegexesEnumerable)
{
if (!string.IsNullOrEmpty(regex)) setRegexes.Add(new Regex(regex));
}
settings.ResourceSetFilters = setRegexes.ToArray();
}
DiscoverResourceOverrides(resources, resourceType);
IList<ResourceRequiredContext> result;
using (var mutex = new Mutex(initiallyOwned: false, "Global\\CombinatorFileAccess"))
{
mutex.WaitOne();
try
{
if (resourceType == ResourceType.Style) result = _combinatorService.CombineStylesheets(resources, settings);
else if (resourceType == ResourceType.JavaScript) result = _combinatorService.CombineScripts(resources, settings);
else return base.BuildRequiredResources(stringResourceType);
}
finally
{
mutex.ReleaseMutex();
}
}
RemoveOriginalResourceShapes(result, resourceType);
return result;
}
catch (Exception ex)
{
if (ex.IsFatal()) throw;
Logger.Error(ex, "Error when combining " + resourceType + " files");
return base.BuildRequiredResources(stringResourceType);
}
}
/// <summary>
/// Checks for overrides of static resources that can cause the actually used resource to be different from the included one
/// </summary>
private void DiscoverResourceOverrides(IList<ResourceRequiredContext> resources, ResourceType resourceType)
{
TraverseResouceShapes(
resources,
resourceType,
(shapeTable, resource, shapeKey) =>
{
var binding = shapeTable.Bindings[shapeKey].BindingSource;
resource.Resource.SetUrl(binding, null);
});
}
/// <summary>
/// Removes shapes corresponding to resources that are included in their original form (i.e. not combined but excluded). This is
/// necessary because otherwise the ordering of a collection of original and combined resources are not kept (original resources are
/// written to the output before the other ones).
/// </summary>
private void RemoveOriginalResourceShapes(IList<ResourceRequiredContext> resources, ResourceType resourceType)
{
TraverseResouceShapes(
resources,
resourceType,
(shapeTable, resource, shapeKey) =>
{
if (shapeKey.EndsWith("-Combined")) return;
// We remove the original shape binding but also re-add it under a different name. The latter operation is needed
// because this way shape override detection (e.g. whether a script is overridden in a child theme) can work.
var binding = shapeTable.Bindings[shapeKey];
shapeTable.Bindings.Remove(shapeKey);
shapeTable.Bindings.Add(CombinedShapeKey(shapeKey), binding);
});
}
private void TraverseResouceShapes(IList<ResourceRequiredContext> resources, ResourceType resourceType, Action<ShapeTable, ResourceRequiredContext, string> processor)
{
var shapeKeyPrefix = resourceType == ResourceType.Style ? "Style__" : "Script__";
var currentTheme = _themeManager.GetRequestTheme(_httpContextAccessor.Current().Request.RequestContext);
var shapeTable = _shapeTableLocator.Lookup(currentTheme.Id);
foreach (var resource in resources)
{
var fullPath = resource.Resource.GetFullPath();
if (!string.IsNullOrEmpty(fullPath))
{
var shapeName = StaticFileBindingStrategy.GetAlternateShapeNameFromFileName(fullPath);
var shapeKey = shapeKeyPrefix + shapeName;
// Simply included CDN stylesheets are not in the ShapeTable, so we have to check
if (shapeTable.Bindings.ContainsKey(shapeKey))
{
processor(shapeTable, resource, shapeKey);
}
else
{
// Maybe the original binding was removed previously and the combined shape binding remains.
shapeKey = CombinedShapeKey(shapeKey);
if (shapeTable.Bindings.ContainsKey(shapeKey))
{
processor(shapeTable, resource, shapeKey);
}
}
}
}
}
private static string CombinedShapeKey(string originalShapeKey)
{
return originalShapeKey + "-Combined";
}
}
}