/// <summary> /// If the file requested is within the rootFolder then a IResourceHandler reference to the file requested will be returned /// otherwise a 404 ResourceHandler will be returned. /// </summary> /// <param name="browser">the browser window that originated the /// request or null if the request did not originate from a browser window /// (for example, if the request came from CefURLRequest).</param> /// <param name="frame">frame that originated the request /// or null if the request did not originate from a browser window /// (for example, if the request came from CefURLRequest).</param> /// <param name="schemeName">the scheme name</param> /// <param name="request">The request. (will not contain cookie data)</param> /// <returns> /// A IResourceHandler /// </returns> IResourceHandler ISchemeHandlerFactory.Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { if (this.schemeName != null && !schemeName.Equals(this.schemeName, StringComparison.OrdinalIgnoreCase)) { return(ResourceHandler.ForErrorMessage(string.Format("SchemeName {0} does not match the expected SchemeName of {1}.", schemeName, this.schemeName), HttpStatusCode.NotFound)); } var uri = new Uri(request.Url); if (this.hostName != null && !uri.Host.Equals(this.hostName, StringComparison.OrdinalIgnoreCase)) { return(ResourceHandler.ForErrorMessage(string.Format("HostName {0} does not match the expected HostName of {1}.", uri.Host, this.hostName), HttpStatusCode.NotFound)); } //Get the absolute path and remove the leading slash var asbolutePath = uri.AbsolutePath.Substring(1); if (string.IsNullOrEmpty(asbolutePath)) { asbolutePath = defaultPage; } var filePath = WebUtility.UrlDecode(Path.GetFullPath(Path.Combine(rootFolder, asbolutePath))); //Check the file requested is within the specified path and that the file exists if (filePath.StartsWith(rootFolder, StringComparison.OrdinalIgnoreCase) && File.Exists(filePath)) { var fileExtension = Path.GetExtension(filePath); var mimeType = ResourceHandler.GetMimeType(fileExtension); var stream = File.OpenRead(filePath); return(ResourceHandler.FromStream(stream, mimeType)); } return(ResourceHandler.ForErrorMessage("File Not Found - " + filePath, HttpStatusCode.NotFound)); }
public IResourceHandler GetResourceHandler(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request) { // Every time we request the main GPM page allow another JS injection if (Regex.Match(request.Url, @"^http[s]?://play\.google\.com/music/listen", RegexOptions.IgnoreCase).Success) { firstJSOnly = true; } if (Regex.Match(request.Url, @"\.js", RegexOptions.IgnoreCase).Success&& Regex.Match(request.Url, @"http", RegexOptions.IgnoreCase).Success&& firstJSOnly) { firstJSOnly = false; using (WebClient webClient = new WebClient()) { // These are the JS files to inject into GPM string custom_interface = Properties.Resources.custom_interface; return(ResourceHandler.FromStream(new MemoryStream(Encoding.UTF8.GetBytes( webClient.DownloadString(request.Url) + ";document.addEventListener('DOMContentLoaded', function () {" + "window.OBSERVER = setInterval(function() { if (document.getElementById('material-vslider')) { clearInterval(window.OBSERVER); " + Properties.Resources.gmusic_min + Properties.Resources.gmusic_theme_min + Properties.Resources.gmusic_mini_player_min + this.getInitCode() + custom_interface + "}}, 10);});")), webClient.ResponseHeaders["Content-Type"])); } } return(null); }
private static ResourceHandler CreateHandler(byte[] bytes) { var handler = ResourceHandler.FromStream(new MemoryStream(bytes), autoDisposeStream: true); handler.Headers.Set("Access-Control-Allow-Origin", "*"); return(handler); }
public IResourceHandler GetResourceHandler(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request) { // Every time we request the main GPM page allow another JS injection if (Regex.Match(request.Url, @"^http[s]?://play\.google\.com/music/listen", RegexOptions.IgnoreCase).Success) { firstJSOnly = true; } if (Regex.Match(request.Url, @"\.js", RegexOptions.IgnoreCase).Success&& Regex.Match(request.Url, @"http", RegexOptions.IgnoreCase).Success&& firstJSOnly) { firstJSOnly = false; using (WebClient webClient = new WebClient()) { // These are the JS files to inject into GPM string dark_theme = Google_Play_Music.Properties.Resources.dark_theme; string custom_interface = Google_Play_Music.Properties.Resources.custom_interface; string mini_player = Google_Play_Music.Properties.Resources.mini_player; Color c = Properties.Settings.Default.CustomColor; string RGB = "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2"); string custom_color = ";(function() {window.CustomColor = '" + RGB + "';})();"; bool controlsOnHover = Properties.Settings.Default.HoverControls; string controlsOnHoverJS = ";(function() {window.hoverControls = " + controlsOnHover.ToString().ToLower() + ";})();"; return(ResourceHandler.FromStream(new MemoryStream(Encoding.UTF8.GetBytes(webClient.DownloadString(request.Url) + ";" + custom_color + controlsOnHoverJS + dark_theme + custom_interface + mini_player)), webClient.ResponseHeaders["Content-Type"])); } } return(null); }
/// <summary> /// Creates resource handler for the given request /// </summary> private IResourceHandler GetResourceHandler(IRequest request) { Uri uri = new Uri(request.Url); //Check if the given scheme is supported if (!supportedSchemes.Any(s => s.Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))) { return(null); } var folders = GetAllSubPath(uri); foreach (var item in folders) { IResourceProvider provider; if (resourceProviders.TryGetValue(item, out provider)) { string extension; var stream = provider.GetResource(request, out extension); if (stream == null) { return(null); } var handler = ResourceHandler.FromStream(stream, ResourceHandler.GetMimeType(extension)); if (provider.IsStaticResource) { this.RegisterHandler(request.Url, handler); } return(handler); } } return(null); }
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { if (schemeName == SchemeName) { String extension = Path.GetExtension(request.Url.ToString()); String mimeType = MimeTypes.MimeTypeMap.GetMimeType(extension); Uri Uri = new Uri(request.Url); var name = typeof(ACTWebSocket_Plugin.ACTWebSocketCore).Module.Name; var assem = typeof(ACTWebSocket_Plugin.ACTWebSocketCore).Module.Assembly; string[] resources = assem.GetManifestResourceNames(); string list = ""; // Build the string of resources. foreach (string resource in resources) { list += resource + "\r\n"; } // example : ACTWebSocket.Core.Resources.img.copy.svg String path = Uri.AbsolutePath.ToString(); path = Path.GetDirectoryName(path).Substring(1) + "/" + Path.GetFileNameWithoutExtension(path); path = path.Replace("/", ".").Replace("\\", "."); path = Path.GetFileNameWithoutExtension(name) + "." + path; path = path + extension; Stream stream = typeof(ACTWebSocket_Plugin.ACTWebSocketCore).Module.Assembly.GetManifestResourceStream(path); return(ResourceHandler.FromStream(stream, mimeType)); } return(new CefSharpSchemeHandler()); }
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { var uri = new Uri(request.Url); var filePath = uri.AbsolutePath; if (filePath.StartsWith("/")) { filePath = filePath.Substring(1); } if (filePath.Contains("?")) { filePath = filePath.Substring(0, filePath.IndexOf("?")); } var fileExtension = Path.GetExtension(filePath); var mimeType = ResourceHandler.GetMimeType(fileExtension); var domainName = uri.Host; var buff = PakHelper.Instance.GetResource(domainName, filePath); var stream = new MemoryStream(); stream.Write(buff, 0, buff.Length); stream.Position = 0; var result = ResourceHandler.FromStream(stream, mimeType); result.AutoDisposeStream = true; return(result); }
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { if (schemeName == "hs") { var baseDir = Environment.CurrentDirectory + "\\plugins\\ui\\html\\"; var str = request.Url.Replace("hs://res/", "").Split('?')[0]; var filePath = str; try { var mimetype = ""; switch (str.Split('.').Last()) { case "html": { mimetype = "text/html"; break; } case "css": { mimetype = "text/css"; break; } case "js": { mimetype = "text/javascript"; break; } default: { mimetype = "application/octet-stream"; break; } } //return ResourceHandler.FromFilePath(filePath, mimetype); var bundleName = str.Split('/').First(); return(ResourceHandler.FromStream( UIPlugin.PluginManager.GetResourceManager().GetFileStream(bundleName, filePath.Replace(bundleName + "/", "")), mimetype)); } catch (FileNotFoundException e) { _logger.Warn(e); return(ResourceHandler.ForErrorMessage("File not found.", HttpStatusCode.NotFound)); } //return ResourceHandler.ForErrorMessage("File not found.", HttpStatusCode.NotFound); } return(new ResourceHandler()); }
IResourceHandler Error(string error, HttpStatusCode code) { var stream = ResourceHandler.GetMemoryStream(error, Encoding.UTF8); var resourceHandler = ResourceHandler.FromStream(stream); resourceHandler.StatusCode = (int)code; Logger.Error("[OVERLAY] Load Error for plugin:// scheme: " + error); return(resourceHandler); }
private void OnResourceStreamRegistered(string key, Stream value) { Uri url = new Uri(key, UriKind.RelativeOrAbsolute); if (!url.IsAbsoluteUri) { url = new Uri(new Uri("http://localhost"), url); } var extension = Path.GetExtension(key); var handler = ResourceHandler.FromStream(value, ResourceHandler.GetMimeType(extension)); resourceFactory.RegisterHandler(url.AbsoluteUri, handler); }
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { Uri uri = new Uri(request.Url); if (!PluginManager.Plugins.ContainsKey(uri.Host.ToLower())) { return(Error("Could not find plugin matching " + uri.Host, HttpStatusCode.NotFound)); } string basePath = PluginManager.Plugins[uri.Host].BasePath; if (basePath == null) { return(Error("This scheme handler has a base path of null and cannot continue processing plugin:// requests", HttpStatusCode.NotImplemented)); } if (!schemeName.Equals("plugin", StringComparison.OrdinalIgnoreCase)) { return(Error(string.Format("SchemeName {0} does not match the expected SchemeName of {1}.", schemeName, "plugin"), HttpStatusCode.NotFound)); } Logger.Trace("Got request with plugin:// scheme: " + request.Url); string absolutePath = uri.AbsolutePath.Substring(1); if (string.IsNullOrEmpty(absolutePath)) { return(Error("Empty Path", HttpStatusCode.NotFound)); } string filePath = PathUtilities.GetTruePath(basePath, absolutePath); if (filePath.EndsWith("/") || filePath.EndsWith("\\")) { filePath = filePath.Substring(0, filePath.Length - 1); } if (PathUtilities.IsInFolder(basePath, filePath)) { string ext = Path.GetExtension(filePath); string mime = ResourceHandler.GetMimeType(ext); var stream = File.OpenRead(filePath); return(ResourceHandler.FromStream(stream, mime)); } return(Error(String.Format("File not found: {0}", filePath), HttpStatusCode.NotFound)); }
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { var uri = new Uri(request.Url); var file = uri.Authority + uri.AbsolutePath; var executingAssembly = Assembly.GetExecutingAssembly(); var resourcePath = "CefSharp.MinimalExample.Wpf." + file.Replace("/", "."); if (executingAssembly.GetManifestResourceInfo(resourcePath) != null) { var resourceStream = executingAssembly.GetManifestResourceStream(resourcePath); var memoryStream = new MemoryStream(); resourceStream.CopyTo(memoryStream); resourceStream.Close(); memoryStream.Position = 0; return(ResourceHandler.FromStream(memoryStream)); } return(new ResourceHandler()); }
private void InitializeResourceStreams(DynamoModel model, LibraryViewCustomization customization) { //TODO: Remove the parameter after testing. //For testing purpose. resourceFactory = new ResourceHandlerFactory(model.Logger); //Register the resource stream registered through the LibraryViewCustomization foreach (var item in customization.Resources) { OnResourceStreamRegistered(item.Key, item.Value); } //Setup the event handler for resource registration customization.ResourceStreamRegistered += OnResourceStreamRegistered; resourceFactory.RegisterProvider("/dist", new DllResourceProvider("http://localhost/dist", "Dynamo.LibraryUI.web.library")); resourceFactory.RegisterProvider(IconUrl.ServiceEndpoint, new IconResourceProvider(model.PathManager)); { var url = "http://localhost/library.html"; var resource = "Dynamo.LibraryUI.web.library.library.html"; var stream = LoadResource(resource); resourceFactory.RegisterHandler(url, ResourceHandler.FromStream(stream)); } //Register provider for node data resourceFactory.RegisterProvider("/loadedTypes", new NodeItemDataProvider(model.SearchModel)); //Register provider for layout spec resourceFactory.RegisterProvider("/layoutSpecs", new LayoutSpecProvider(customization, "Dynamo.LibraryUI.web.library.layoutSpecs.json")); //Setup the event observer for NodeSearchModel to update customization/spec provider. observer = SetupSearchModelEventsObserver(model.SearchModel, this, customization); //Register provider for searching node data resourceFactory.RegisterProvider(SearchResultDataProvider.serviceIdentifier, new SearchResultDataProvider(model.SearchModel)); }
public IResourceHandler Create( IBrowser browser, IFrame frame, string schemeName, IRequest request) { string absolutePath = new Uri(request.Url).AbsolutePath; Uri uriResource; if (!TheForksShemeFactory._pages.TryGetValue(request.Url, out uriResource)) { return((IResourceHandler)null); } string extension = Path.GetExtension(absolutePath); StreamResourceInfo resourceStream = Application.GetResourceStream(uriResource); if (resourceStream == null) { return((IResourceHandler)null); } return((IResourceHandler)ResourceHandler.FromStream(resourceStream.Stream, ResourceHandler.GetMimeType(extension))); }
/// <summary> /// Create an instance of FileSystemResourceHandler. /// </summary> /// <param name="browser">The browser window that originated the request or null if the request did not originate from a browser window (for example, if the request came from CefURLRequest).</param> /// <param name="frame">Frame that originated the request or null if the request did not originate from a browser window (for example, if the request came from CefURLRequest).</param> /// <param name="schemeName">The scheme name</param> /// <param name="request">The request. (will not contain cookie data)</param> /// <returns>Return a new FileSystemResourceHandler instance to handle the request or an empty reference to allow default handling of the request.</returns> public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { // Only handle fs scheme. if (string.Compare(schemeName, SchemeName, true, CultureInfo.InvariantCulture) != 0) { return(ResourceHandler.ForErrorMessage($"Invalid scheme [{schemeName}].", HttpStatusCode.BadRequest)); } var uri = new Uri(request.Url); var root = uri.Authority; // If the root of the path is a system volume then add the volume separator ":" // else it will be consider as just another directory. if (_volumes.Any(v => v.StartsWith(root, StringComparison.InvariantCultureIgnoreCase))) { root = root + Path.VolumeSeparatorChar; } var filepath = root + Uri.UnescapeDataString(uri.AbsolutePath); if (File.Exists(filepath)) { // Read file and then copy to a separate memory stream so the file isn't locked. using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { #pragma warning disable CA2000 // Dispose objects before losing scope // Don't dispose the stream here, ResourceHandler.FromStream autoDisposeStream is set to false by default. // The comment indicates "you will only be able to serve one request" ¯\_(ツ)_/¯ var ms = new MemoryStream(); #pragma warning restore CA2000 // Dispose objects before losing scope stream.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); return(ResourceHandler.FromStream(ms, Cef.GetMimeType(Path.GetExtension(filepath)), false)); } } return(ResourceHandler.ForErrorMessage("File not found.", HttpStatusCode.NotFound)); }
protected override IResourceHandler GetResourceHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request) { string url = request.Url.Substring("http://HuiDesktop/".Length); if (url.Contains('?')) { url = url.Substring(0, url.IndexOf('?')); } if (url.Contains('#')) { url = url.Substring(0, url.IndexOf('#')); } if (fileIndex.ContainsKey(url) == false) { return(ResourceHandler.ForErrorMessage("", System.Net.HttpStatusCode.NotFound)); } var ms = fileIndex[url]; lock (ms) { ms.Position = 0; return(ResourceHandler.FromStream(ms, FileContentType.GetMimeType(url.Substring(url.LastIndexOf('.'))))); } }
/// <summary> /// If the file requested is within the rootFolder then a IResourceHandler reference to the file requested will be returned /// otherwise a 404 ResourceHandler will be returned. /// </summary> /// <param name="browser">the browser window that originated the /// request or null if the request did not originate from a browser window /// (for example, if the request came from CefURLRequest).</param> /// <param name="frame">frame that originated the request /// or null if the request did not originate from a browser window /// (for example, if the request came from CefURLRequest).</param> /// <param name="schemeName">the scheme name</param> /// <param name="request">The request. (will not contain cookie data)</param> /// <returns> /// A IResourceHandler /// </returns> protected virtual IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { if (this.schemeName != null && !schemeName.Equals(this.schemeName, StringComparison.OrdinalIgnoreCase)) { return(ResourceHandler.ForErrorMessage(string.Format("SchemeName {0} does not match the expected SchemeName of {1}.", schemeName, this.schemeName), HttpStatusCode.NotFound)); } var uri = new Uri(request.Url); if (this.hostName != null && !uri.Host.Equals(this.hostName, StringComparison.OrdinalIgnoreCase)) { return(ResourceHandler.ForErrorMessage(string.Format("HostName {0} does not match the expected HostName of {1}.", uri.Host, this.hostName), HttpStatusCode.NotFound)); } //Get the absolute path and remove the leading slash var asbolutePath = uri.AbsolutePath.Substring(1); ResourceLoader loader = null; //Search for ResourceLoader ID # int separator = asbolutePath.IndexOf("/"); int id; if ((separator > -1) && int.TryParse(asbolutePath.Substring(0, separator), out id)) { InteractiveCharts.ResourceLoaders.TryGetValue(id, out loader); asbolutePath = asbolutePath.Substring(separator + 1); //Adjust uri to only contain the file name now } // Get file properties string fileExtension = Path.GetExtension(asbolutePath); var mimeType = GetMimeTypeDelegate(fileExtension); Stream stream = null; // Check for resources that are loaded by the ResourceLoader if (loader != null) { if (asbolutePath == "config.js") { stream = loader.LoadConfig(); } else if (asbolutePath == "data.json") { stream = loader.LoadData(); } } // If no stream has been loaded yet, attempt to load from an internal assembly resource. if (stream == null) { try { var assembly = Assembly.GetExecutingAssembly(); stream = assembly.GetManifestResourceStream("InteractiveCharts.Resources." + asbolutePath.Replace('/', '.')); } catch (Exception) { stream = null; } } if (stream != null) { return(ResourceHandler.FromStream(stream, mimeType)); } else { return(ResourceHandler.ForErrorMessage("Resource Not Found - " + uri.AbsolutePath, HttpStatusCode.NotFound)); } }
protected override IResourceHandler GetResourceHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request) { return(ResourceHandler.FromStream(_stream, _contentType, true, _charSet)); }