forked from grandnode/grandnode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPageHeadBuilder.cs
668 lines (557 loc) · 24.5 KB
/
PageHeadBuilder.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
using BundlerMinifier;
using Grand.Core.Domain.Seo;
using Grand.Services.Seo;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace Grand.Framework.UI
{
/// <summary>
/// Page head builder
/// </summary>
public partial class PageHeadBuilder : IPageHeadBuilder
{
#region Fields
private static readonly object s_lock = new object();
private readonly SeoSettings _seoSettings;
private readonly IHostingEnvironment _hostingEnvironment;
private BundleFileProcessor _processor;
private readonly List<string> _titleParts;
private readonly List<string> _metaDescriptionParts;
private readonly List<string> _metaKeywordParts;
private readonly Dictionary<ResourceLocation, List<ScriptReferenceMeta>> _scriptParts;
private readonly Dictionary<ResourceLocation, List<CssReferenceMeta>> _cssParts;
private readonly List<string> _canonicalUrlParts;
private readonly List<string> _headCustomParts;
private readonly List<string> _pageCssClassParts;
private string _editPageUrl;
private string _activeAdminMenuSystemName;
#endregion
#region Ctor
/// <summary>
/// Constuctor
/// </summary>
/// <param name="seoSettings">SEO settings</param>
/// <param name="hostingEnvironment">Hosting environment</param>
public PageHeadBuilder(SeoSettings seoSettings, IHostingEnvironment hostingEnvironment)
{
this._seoSettings = seoSettings;
this._hostingEnvironment = hostingEnvironment;
this._processor = new BundleFileProcessor();
this._titleParts = new List<string>();
this._metaDescriptionParts = new List<string>();
this._metaKeywordParts = new List<string>();
this._scriptParts = new Dictionary<ResourceLocation, List<ScriptReferenceMeta>>();
this._cssParts = new Dictionary<ResourceLocation, List<CssReferenceMeta>>();
this._canonicalUrlParts = new List<string>();
this._headCustomParts = new List<string>();
this._pageCssClassParts = new List<string>();
}
#endregion
#region Utilities
protected virtual string GetBundleFileNameBasingOnModifyTime(string[] filePaths)
{
if (filePaths == null || filePaths.Length == 0)
throw new ArgumentException("parts");
var ticks = filePaths.Where(filePath => File.Exists(filePath)).Select(filePath => { return File.GetLastWriteTimeUtc(filePath).Ticks; });
//calculate hash
var hash = "";
using (SHA256 sha = SHA256.Create())
{
// string concatenation
var hashInput = "";
foreach (var tick in ticks)
{
hashInput += tick;
hashInput += ",";
}
byte[] input = sha.ComputeHash(Encoding.Unicode.GetBytes(hashInput));
hash = WebEncoders.Base64UrlEncode(input);
}
//ensure only valid chars
hash = SeoExtensions.GetSeName(hash);
return hash;
}
#endregion
#region Methods
public virtual void AddTitleParts(string part)
{
if (string.IsNullOrEmpty(part))
return;
_titleParts.Add(part);
}
public virtual void AppendTitleParts(string part)
{
if (string.IsNullOrEmpty(part))
return;
_titleParts.Insert(0, part);
}
public virtual string GenerateTitle(bool addDefaultTitle)
{
string result = "";
var specificTitle = string.Join(_seoSettings.PageTitleSeparator, _titleParts.AsEnumerable().Reverse().ToArray());
if (!String.IsNullOrEmpty(specificTitle))
{
if (addDefaultTitle)
{
//store name + page title
switch (_seoSettings.PageTitleSeoAdjustment)
{
case PageTitleSeoAdjustment.PagenameAfterStorename:
{
result = string.Join(_seoSettings.PageTitleSeparator, _seoSettings.DefaultTitle, specificTitle);
}
break;
case PageTitleSeoAdjustment.StorenameAfterPagename:
default:
{
result = string.Join(_seoSettings.PageTitleSeparator, specificTitle, _seoSettings.DefaultTitle);
}
break;
}
}
else
{
//page title only
result = specificTitle;
}
}
else
{
//store name only
result = _seoSettings.DefaultTitle;
}
return result;
}
public virtual void AddMetaDescriptionParts(string part)
{
if (string.IsNullOrEmpty(part))
return;
_metaDescriptionParts.Add(part);
}
public virtual void AppendMetaDescriptionParts(string part)
{
if (string.IsNullOrEmpty(part))
return;
_metaDescriptionParts.Insert(0, part);
}
public virtual string GenerateMetaDescription()
{
var metaDescription = string.Join(", ", _metaDescriptionParts.AsEnumerable().Reverse().ToArray());
var result = !String.IsNullOrEmpty(metaDescription) ? metaDescription : _seoSettings.DefaultMetaDescription;
return result;
}
public virtual void AddMetaKeywordParts(string part)
{
if (string.IsNullOrEmpty(part))
return;
_metaKeywordParts.Add(part);
}
public virtual void AppendMetaKeywordParts(string part)
{
if (string.IsNullOrEmpty(part))
return;
_metaKeywordParts.Insert(0, part);
}
public virtual string GenerateMetaKeywords()
{
var metaKeyword = string.Join(", ", _metaKeywordParts.AsEnumerable().Reverse().ToArray());
var result = !String.IsNullOrEmpty(metaKeyword) ? metaKeyword : _seoSettings.DefaultMetaKeywords;
return result;
}
public virtual void AddScriptParts(ResourceLocation location, string src, string debugSrc, bool excludeFromBundle, bool isAsync)
{
if (!_scriptParts.ContainsKey(location))
_scriptParts.Add(location, new List<ScriptReferenceMeta>());
if (string.IsNullOrEmpty(src))
return;
if (String.IsNullOrEmpty(debugSrc))
debugSrc = src;
_scriptParts[location].Add(new ScriptReferenceMeta
{
ExcludeFromBundle = excludeFromBundle,
IsAsync = isAsync,
Src = src,
DebugSrc = debugSrc
});
}
public virtual void AppendScriptParts(ResourceLocation location, string src, string debugSrc, bool excludeFromBundle, bool isAsync)
{
if (!_scriptParts.ContainsKey(location))
_scriptParts.Add(location, new List<ScriptReferenceMeta>());
if (string.IsNullOrEmpty(src))
return;
if (String.IsNullOrEmpty(debugSrc))
debugSrc = src;
_scriptParts[location].Insert(0, new ScriptReferenceMeta
{
ExcludeFromBundle = excludeFromBundle,
IsAsync = isAsync,
Src = src,
DebugSrc = debugSrc
});
}
public virtual string GenerateScripts(IUrlHelper urlHelper, ResourceLocation location, bool? bundleFiles = null)
{
if (!_scriptParts.ContainsKey(location) || _scriptParts[location] == null)
return "";
if (!_scriptParts.Any())
return "";
var debugModel = _hostingEnvironment.IsDevelopment();
if (!bundleFiles.HasValue)
{
//use setting if no value is specified
bundleFiles = _seoSettings.EnableJsBundling;
}
if (bundleFiles.Value)
{
var partsToBundle = _scriptParts[location]
.Where(x => !x.ExcludeFromBundle)
.Distinct()
.ToArray();
var partsToDontBundle = _scriptParts[location]
.Where(x => x.ExcludeFromBundle)
.Distinct()
.ToArray();
var result = new StringBuilder();
//parts to bundle
if (partsToBundle.Any())
{
//ensure \bundles directory exists
Directory.CreateDirectory(Path.Combine(_hostingEnvironment.WebRootPath, "bundles"));
var srcPath = string.Empty;
var bundle = new Bundle();
foreach (var item in partsToBundle)
{
var src = debugModel ? item.DebugSrc : item.Src;
src = urlHelper.Content(src);
//check whether this file exists.
if(Grand.Core.OperatingSystem.IsWindows())
srcPath = Path.Combine(_hostingEnvironment.ContentRootPath, src.Remove(0, 1).Replace("/", "\\"));
else
srcPath = Path.Combine(_hostingEnvironment.ContentRootPath, src.Remove(0, 1));
if (File.Exists(srcPath))
{
//remove starting /
src = src.Remove(0, 1);
if (File.Exists(srcPath))
item.FilePath = srcPath;
}
else
{
//if not, it should be stored into /wwwroot directory
src = "wwwroot/" + src;
if(Grand.Core.OperatingSystem.IsWindows())
srcPath = Path.Combine(_hostingEnvironment.ContentRootPath, src.Replace("/", "\\").Replace("\\\\", "\\"));
else
srcPath = Path.Combine(_hostingEnvironment.ContentRootPath, src);
if (File.Exists(srcPath))
item.FilePath = srcPath;
}
bundle.InputFiles.Add(src);
}
//output file name
var outputFileName = GetBundleFileNameBasingOnModifyTime(partsToBundle.Select(x => { return x.FilePath; }).ToArray());
bundle.OutputFileName = "wwwroot/bundles/" + outputFileName + ".js";
//save
string configFilePath = _hostingEnvironment.ContentRootPath + (Grand.Core.OperatingSystem.IsWindows() ? "\\" : "/") + outputFileName + ".json";
bundle.FileName = configFilePath;
var bundleDirectory = Path.Combine(_hostingEnvironment.WebRootPath, "bundles");
var filePaths = Directory.EnumerateFiles(bundleDirectory);
var fileNames = filePaths.Select(x => x.Substring(x.LastIndexOf((Grand.Core.OperatingSystem.IsWindows() ? "\\" : "/")) + 1));
if (!fileNames.Any(x=>x.Contains(outputFileName)))
{
lock (s_lock)
{
//process
_processor.Process(configFilePath, new List<Bundle> { bundle });
}
}
//render
if (File.Exists(bundleDirectory + (Grand.Core.OperatingSystem.IsWindows() ? "\\" : "/") + outputFileName + ".min.js"))
result.AppendFormat("<script src=\"{0}\"></script>", urlHelper.Content("~/bundles/" + outputFileName + ".min.js"));
else
result.AppendFormat("<script src=\"{0}\"></script>", urlHelper.Content("~/bundles/" + outputFileName + ".js"));
result.Append(Environment.NewLine);
}
//parts to not bundle
foreach (var item in partsToDontBundle)
{
var src = debugModel ? item.DebugSrc : item.Src;
result.AppendFormat("<script {1} src=\"{0}\"></script>", urlHelper.Content(src), item.IsAsync ? "async" : "");
result.Append(Environment.NewLine);
}
return result.ToString();
}
else
{
//bundling is disabled
var result = new StringBuilder();
foreach (var item in _scriptParts[location].Distinct())
{
var src = debugModel ? item.DebugSrc : item.Src;
result.AppendFormat("<script {1}src=\"{0}\"></script>", urlHelper.Content(src), item.IsAsync ? "async " : "");
result.Append(Environment.NewLine);
}
return result.ToString();
}
}
public virtual void AddCssFileParts(ResourceLocation location, string src, string debugSrc, bool excludeFromBundle = false)
{
if (!_cssParts.ContainsKey(location))
_cssParts.Add(location, new List<CssReferenceMeta>());
if (string.IsNullOrEmpty(src))
return;
if (String.IsNullOrEmpty(debugSrc))
debugSrc = src;
_cssParts[location].Add(new CssReferenceMeta
{
ExcludeFromBundle = excludeFromBundle,
Src = src,
DebugSrc = debugSrc
});
}
public virtual void AppendCssFileParts(ResourceLocation location, string src, string debugSrc, bool excludeFromBundle = false)
{
if (!_cssParts.ContainsKey(location))
_cssParts.Add(location, new List<CssReferenceMeta>());
if (string.IsNullOrEmpty(src))
return;
if (String.IsNullOrEmpty(debugSrc))
debugSrc = src;
_cssParts[location].Insert(0, new CssReferenceMeta
{
ExcludeFromBundle = excludeFromBundle,
Src = src,
DebugSrc = debugSrc
});
}
public virtual string GenerateCssFiles(IUrlHelper urlHelper, ResourceLocation location, bool? bundleFiles = null)
{
if (!_cssParts.ContainsKey(location) || _cssParts[location] == null)
return "";
if (!_cssParts.Any())
return "";
var debugModel = _hostingEnvironment.IsDevelopment();
if (!bundleFiles.HasValue)
{
//use setting if no value is specified
bundleFiles = _seoSettings.EnableCssBundling;
}
//CSS bundling is not allowed in virtual directories
if (urlHelper.ActionContext.HttpContext.Request.PathBase.HasValue)
bundleFiles = false;
if (bundleFiles.Value)
{
var partsToBundle = _cssParts[location]
.Where(x => !x.ExcludeFromBundle)
.Distinct()
.ToArray();
var partsToDontBundle = _cssParts[location]
.Where(x => x.ExcludeFromBundle)
.Distinct()
.ToArray();
var result = new StringBuilder();
//parts to bundle
if (partsToBundle.Any())
{
//ensure \bundles directory exists
Directory.CreateDirectory(Path.Combine(_hostingEnvironment.WebRootPath, "bundles"));
var bundle = new Bundle();
foreach (var item in partsToBundle)
{
var src = debugModel ? item.DebugSrc : item.Src;
src = urlHelper.Content(src);
//check whether this file exists
var srcPath = Grand.Core.OperatingSystem.IsWindows() ?
Path.Combine(_hostingEnvironment.ContentRootPath, src.Remove(0, 1).Replace("/", "\\")) :
Path.Combine(_hostingEnvironment.ContentRootPath, src.Remove(0, 1));
if (File.Exists(srcPath))
{
//remove starting /
src = src.Remove(0, 1);
if (File.Exists(srcPath))
item.FilePath = srcPath;
}
else
{
//if not, it should be stored into /wwwroot directory
src = "wwwroot" + src;
if(Grand.Core.OperatingSystem.IsWindows())
srcPath = Path.Combine(_hostingEnvironment.ContentRootPath, src.Replace("/", "\\").Replace("\\\\", "\\"));
else
srcPath = Path.Combine(_hostingEnvironment.ContentRootPath, src);
if (File.Exists(srcPath))
item.FilePath = srcPath;
}
bundle.InputFiles.Add(src);
}
//output file name
var outputFileName = GetBundleFileNameBasingOnModifyTime(partsToBundle.Select(x => { return x.FilePath; }).ToArray());
bundle.OutputFileName = "wwwroot/bundles/" + outputFileName + ".css";
//save
string configFilePath = _hostingEnvironment.ContentRootPath + (Grand.Core.OperatingSystem.IsWindows() ? "\\" : "/") + outputFileName + ".json";
bundle.FileName = configFilePath;
var bundleDirectory = Path.Combine(_hostingEnvironment.WebRootPath, "bundles");
var filePaths = Directory.EnumerateFiles(bundleDirectory);
var fileNames = filePaths.Select(x => x.Substring(x.LastIndexOf((Grand.Core.OperatingSystem.IsWindows() ? "\\" : "/")) + 1));
if (!fileNames.Any(x=>x.Contains(outputFileName)))
{
lock (s_lock)
{
//process
_processor.Process(configFilePath, new List<Bundle> { bundle });
}
}
//render
if (File.Exists(bundleDirectory+ (Grand.Core.OperatingSystem.IsWindows() ? "\\" : "/") + outputFileName + ".min.css"))
result.AppendFormat("<link href=\"{0}\" rel=\"stylesheet\" type=\"{1}\" />", urlHelper.Content("~/bundles/" + outputFileName + ".min.css"), "text/css");
else
result.AppendFormat("<link href=\"{0}\" rel=\"stylesheet\" type=\"{1}\" />", urlHelper.Content("~/bundles/" + outputFileName + ".css"), "text/css");
result.Append(Environment.NewLine);
}
//parts not to bundle
foreach (var item in partsToDontBundle)
{
var src = debugModel ? item.DebugSrc : item.Src;
result.AppendFormat("<link href=\"{0}\" rel=\"stylesheet\" type=\"{1}\" />", urlHelper.Content(src), "text/css");
result.Append(Environment.NewLine);
}
return result.ToString();
}
else
{
//bundling is disabled
var result = new StringBuilder();
foreach (var item in _cssParts[location].Distinct())
{
var src = debugModel ? item.DebugSrc : item.Src;
result.AppendFormat("<link href=\"{0}\" rel=\"stylesheet\" type=\"{1}\" />", urlHelper.Content(src), "text/css");
result.AppendLine();
}
return result.ToString();
}
}
public virtual void AddCanonicalUrlParts(string part)
{
if (string.IsNullOrEmpty(part))
return;
_canonicalUrlParts.Add(part);
}
public virtual void AppendCanonicalUrlParts(string part)
{
if (string.IsNullOrEmpty(part))
return;
_canonicalUrlParts.Insert(0, part);
}
public virtual string GenerateCanonicalUrls()
{
var result = new StringBuilder();
foreach (var canonicalUrl in _canonicalUrlParts)
{
result.AppendFormat("<link rel=\"canonical\" href=\"{0}\" />", canonicalUrl);
result.Append(Environment.NewLine);
}
return result.ToString();
}
public virtual void AddHeadCustomParts(string part)
{
if (string.IsNullOrEmpty(part))
return;
_headCustomParts.Add(part);
}
public virtual void AppendHeadCustomParts(string part)
{
if (string.IsNullOrEmpty(part))
return;
_headCustomParts.Insert(0, part);
}
public virtual string GenerateHeadCustom()
{
//use only distinct rows
var distinctParts = _headCustomParts.Distinct().ToList();
if (!distinctParts.Any())
return "";
var result = new StringBuilder();
foreach (var path in distinctParts)
{
result.Append(path);
result.Append(Environment.NewLine);
}
return result.ToString();
}
public virtual void AddPageCssClassParts(string part)
{
if (string.IsNullOrEmpty(part))
return;
_pageCssClassParts.Add(part);
}
public virtual void AppendPageCssClassParts(string part)
{
if (string.IsNullOrEmpty(part))
return;
_pageCssClassParts.Insert(0, part);
}
public virtual string GeneratePageCssClasses()
{
string result = string.Join(" ", _pageCssClassParts.AsEnumerable().Reverse().ToArray());
return result;
}
/// <summary>
/// Specify "edit page" URL
/// </summary>
/// <param name="url">URL</param>
public virtual void AddEditPageUrl(string url)
{
_editPageUrl = url;
}
/// <summary>
/// Get "edit page" URL
/// </summary>
/// <returns>URL</returns>
public virtual string GetEditPageUrl()
{
return _editPageUrl;
}
/// <summary>
/// Specify system name of admin menu item that should be selected (expanded)
/// </summary>
/// <param name="systemName">System name</param>
public virtual void SetActiveMenuItemSystemName(string systemName)
{
_activeAdminMenuSystemName = systemName;
}
/// <summary>
/// Get system name of admin menu item that should be selected (expanded)
/// </summary>
/// <returns>System name</returns>
public virtual string GetActiveMenuItemSystemName()
{
return _activeAdminMenuSystemName;
}
#endregion
#region Nested classes
private class ScriptReferenceMeta
{
public bool ExcludeFromBundle { get; set; }
public bool IsAsync { get; set; }
public string Src { get; set; }
public string DebugSrc { get; set; }
public string FilePath { get; set; }
}
private class CssReferenceMeta
{
public bool ExcludeFromBundle { get; set; }
public string Src { get; set; }
public string DebugSrc { get; set; }
public string FilePath { get; set; }
}
#endregion
}
}