CustomResourceSchemeHandlerFactory.cs 1.5 KB

123456789101112131415161718192021222324252627282930
  1. using CefSharp;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.IO;
  5. using System.Linq;
  6. namespace CefSharpWrap.CustomResource
  7. {
  8. internal class CustomResourceSchemeHandlerFactory : ISchemeHandlerFactory
  9. {
  10. internal static readonly ConcurrentDictionary<string, Tuple<string, IBytesProvider>> PathResources = new ConcurrentDictionary<string, Tuple<string, IBytesProvider>>();
  11. internal static readonly ConcurrentDictionary<string, ICustomResourceResolver> PathPrefixResolvers = new ConcurrentDictionary<string, ICustomResourceResolver>();
  12. public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
  13. {
  14. var path = new Uri(request.Url).LocalPath;
  15. if (PathResources.TryGetValue(path, out var tuple)) return new ResourceHandler(tuple.Item1, new MemoryStream(tuple.Item2.GetBytes()), true);
  16. var pathPrefix = PathPrefixResolvers.Keys.FirstOrDefault(p => path.StartsWith(p));
  17. if (null == pathPrefix) return null;
  18. var keys = PathPrefixResolvers.Keys.Where(p => path.StartsWith(p)).OrderByDescending(p => p.Length);
  19. return keys
  20. .Select(key => PathPrefixResolvers[key].Resolve(path.Substring(pathPrefix.Length)))
  21. .Where(result => null != result)
  22. .Select(result => new ResourceHandler(result.Mime, result.Stream, false == result.Reuseable))
  23. .FirstOrDefault();
  24. }
  25. }
  26. }