|
| 1 | +using Microsoft.AspNetCore.Hosting; |
| 2 | +using Microsoft.AspNetCore.Mvc; |
| 3 | +using Microsoft.AspNetCore.Razor.TagHelpers; |
| 4 | +using Microsoft.Extensions.Caching.Memory; |
| 5 | +using Microsoft.Extensions.FileProviders; |
| 6 | +using Microsoft.Extensions.Hosting; |
| 7 | +using System.Collections.Generic; |
| 8 | +using System.IO; |
| 9 | +using System.Linq; |
| 10 | +using System.Threading.Tasks; |
| 11 | + |
| 12 | +namespace TerribleDev.Blog.Web.Taghelpers |
| 13 | +{ |
| 14 | + [HtmlTargetElement("inline-script")] |
| 15 | + public class InlineScriptTagHelper : TagHelper |
| 16 | + { |
| 17 | + [HtmlAttributeName("src")] |
| 18 | + public string Src { get; set; } |
| 19 | + |
| 20 | + private IWebHostEnvironment HostingEnvironment { get; } |
| 21 | + private IMemoryCache Cache { get; } |
| 22 | + |
| 23 | + |
| 24 | + |
| 25 | + public InlineScriptTagHelper(IWebHostEnvironment hostingEnvironment, IMemoryCache cache) |
| 26 | + { |
| 27 | + HostingEnvironment = hostingEnvironment; |
| 28 | + Cache = cache; |
| 29 | + } |
| 30 | + |
| 31 | + |
| 32 | + public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) |
| 33 | + { |
| 34 | + var paths = Src.Split(','); |
| 35 | + |
| 36 | + // Get the value from the cache, or compute the value and add it to the cache |
| 37 | + var fileContent = await Cache.GetOrCreateAsync("InlineScriptTagHelper-" + paths, async entry => |
| 38 | + { |
| 39 | + var fileProvider = HostingEnvironment.WebRootFileProvider; |
| 40 | + var result = paths.Select(async path => { |
| 41 | + if(HostingEnvironment.IsDevelopment()) |
| 42 | + { |
| 43 | + var changeToken = fileProvider.Watch(path); |
| 44 | + entry.AddExpirationToken(changeToken); |
| 45 | + } |
| 46 | + |
| 47 | + entry.SetPriority(CacheItemPriority.NeverRemove); |
| 48 | + |
| 49 | + var file = fileProvider.GetFileInfo(path); |
| 50 | + if (file == null || !file.Exists) |
| 51 | + return null; |
| 52 | + |
| 53 | + return await ReadFileContent(file); |
| 54 | + }); |
| 55 | + var allFinished = await Task.WhenAll(result); |
| 56 | + return string.Join("\n", allFinished); |
| 57 | + }); |
| 58 | + |
| 59 | + if (fileContent == null) |
| 60 | + { |
| 61 | + output.SuppressOutput(); |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + output.TagName = "script"; |
| 66 | + output.Attributes.RemoveAll("href"); |
| 67 | + output.Content.AppendHtml(fileContent); |
| 68 | + } |
| 69 | + |
| 70 | + private static async Task<string> ReadFileContent(IFileInfo file) |
| 71 | + { |
| 72 | + using (var stream = file.CreateReadStream()) |
| 73 | + using (var textReader = new StreamReader(stream)) |
| 74 | + { |
| 75 | + return await textReader.ReadToEndAsync(); |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments