/// <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)) { var invalidSchemeName = ResourceHandler.FromString(string.Format("SchemeName {0} does not match the expected SchemeName of {1}.", schemeName, this.schemeName)); invalidSchemeName.StatusCode = (int)HttpStatusCode.NotFound; return(invalidSchemeName); } var uri = new Uri(request.Url); if (this.hostName != null && !uri.Host.Equals(this.hostName, StringComparison.OrdinalIgnoreCase)) { var invalidHostName = ResourceHandler.FromString(string.Format("HostName {0} does not match the expected HostName of {1}.", uri.Host, this.hostName)); invalidHostName.StatusCode = (int)HttpStatusCode.NotFound; return(invalidHostName); } //Get the absolute path and remove the leading slash var asbolutePath = uri.AbsolutePath.Substring(1); if (string.IsNullOrEmpty(asbolutePath)) { asbolutePath = defaultPage; } var filePath = 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); return(ResourceHandler.FromFilePath(filePath, mimeType)); } var fileNotFoundResourceHandler = ResourceHandler.FromString("File Not Found - " + filePath); fileNotFoundResourceHandler.StatusCode = (int)HttpStatusCode.NotFound; return(fileNotFoundResourceHandler); }
public bool ProcessRequestAsync(IRequest request, ICallback callback) { var uri = new Uri(request.Url); var fileName = uri.ToString().Substring(6); Uri u = ResourceHelper.GetResourceUri(fileName); if (u != null) { Task.Run(() => { using (callback) { try { StreamResourceInfo info = Application.GetResourceStream(u); byte[] buffer = new byte[info.Stream.Length]; info.Stream.Read(buffer, 0, buffer.Length); stream = new MemoryStream(buffer); var fileExtension = Path.GetExtension(fileName); mimeType = ResourceHandler.GetMimeType(fileExtension); callback.Continue(); } catch { //todo: unknown image } } }); return(true); } else { callback.Dispose(); } return(false); }
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { //Notes: // - The 'host' portion is entirely ignored by this scheme handler. // - If you register a ISchemeHandlerFactory for http/https schemes you should also specify a domain name // - Avoid doing lots of processing in this method as it will affect performance. // - Use the Default ResourceHandler implementation var uri = new Uri(request.Url); var fileName = uri.AbsolutePath; //Load a file directly from Disk if (fileName.EndsWith("CefSharp.Core.xml", StringComparison.OrdinalIgnoreCase)) { //Convenient helper method to lookup the mimeType var mimeType = ResourceHandler.GetMimeType(".xml"); //Load a resource handler for CefSharp.Core.xml //mimeType is optional and will default to text/html return(ResourceHandler.FromFilePath("CefSharp.Core.xml", mimeType)); } if (uri.Host == "cefsharp.com" && schemeName == "https" && (string.Equals(fileName, "/PostDataTest.html", StringComparison.OrdinalIgnoreCase) || string.Equals(fileName, "/PostDataAjaxTest.html", StringComparison.OrdinalIgnoreCase))) { return(new CefSharpSchemeHandler()); } if (string.Equals(fileName, "/EmptyResponseFilterTest.html", StringComparison.OrdinalIgnoreCase)) { return(ResourceHandler.FromString("", ".html")); } string resource; if (ResourceDictionary.TryGetValue(fileName, out resource) && !string.IsNullOrEmpty(resource)) { var fileExtension = Path.GetExtension(fileName); return(ResourceHandler.FromString(resource, includePreamble: true, mimeType: ResourceHandler.GetMimeType(fileExtension))); } return(null); }
bool IResourceHandler.ProcessRequest(IRequest request, ICallback callback) { var uri = new Uri(request.Url); string fullPath = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, uri.Authority + uri.AbsolutePath); if (File.Exists(fullPath)) { stream = new MemoryStream(File.ReadAllBytes(fullPath)); var fileExtension = Path.GetExtension(uri.AbsolutePath); mimeType = ResourceHandler.GetMimeType(fileExtension); callback.Continue(); return(true); } else { HWLogger.DEFAULT.Error("error:can not find filename:" + Path.GetFullPath(fullPath)); callback.Dispose(); return(false); } }
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { if (_basePath == null) { return(Error("This scheme handler has a base path of null and cannot continue processing " + _schemeName + ":// requests", HttpStatusCode.NotImplemented)); } if (_schemeName != null && !schemeName.Equals(_schemeName, StringComparison.OrdinalIgnoreCase)) { return(Error(string.Format("SchemeName {0} does not match the expected SchemeName of {1}.", schemeName, _schemeName), HttpStatusCode.NotFound)); } Logger.Trace("Got request with " + _schemeName + ":// scheme: " + request.Url); Uri uri = new Uri(request.Url); string absolutePath = uri.Host + "/" + 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 override CefReturnValue ProcessRequestAsync(IRequest request, ICallback callback) { using (callback) { var url = request.Url; var content_path = url.Replace(@"/", "").Replace(@"embeddedresource:", ""); var asm_name = Assembly.GetExecutingAssembly().GetName().Name; var resource_path = $@"{asm_name}.Content.{content_path}"; var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource_path); if (stream != null) { MimeType = ResourceHandler.GetMimeType(System.IO.Path.GetExtension(content_path)); Stream = stream; ResponseLength = stream.Length; StatusCode = (int)System.Net.HttpStatusCode.OK; callback.Continue(); } } return(CefReturnValue.Continue); }
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { Uri uri = new Uri(request.Url); string location; string extension; if (uri.AbsolutePath == "/") { location = uri.Host; extension = Path.GetExtension(uri.Host); } else { string[] dirs = { uri.Host, uri.AbsolutePath }; extension = Path.GetExtension(uri.AbsolutePath.Split('/').Last()); location = $"{uri.Host}/{uri.AbsolutePath}"; } string mime = ResourceHandler.GetMimeType(extension); string path = FSHelper.NormalizeLocation($"{Root}/{location}"); return(ResourceHandler.FromFilePath(path, mime)); }
public CustomResourceHandler(string filename) { if (AcRootDirectory.Instance.Value == null || !FileUtils.IsAffectedBy(filename, Path.Combine(AcRootDirectory.Instance.RequireValue, "content"))) { _data = null; _mimeType = @"application/octet-stream"; return; } try { _data = File.Exists(filename) ? File.OpenRead(filename) : null; } catch (Exception e) { Logging.Warning(e); _data = null; } try { _mimeType = ResourceHandler.GetMimeType(Path.GetExtension(filename)); } catch (Exception e) { Logging.Warning(e); _mimeType = @"application/octet-stream"; } }
// // Summary: // Begin processing the request. // // Parameters: // request: // The request object. // // callback: // The callback used to Continue or Cancel the request (async). // // Returns: // To handle the request return true and call CefSharp.ICallback.Continue() // once the response header information is available CefSharp.ICallback.Continue() // can also be called from inside this method if header information is available // immediately). To cancel the request return false. public bool ProcessRequest(IRequest request, ICallback callback) { uri = new Uri(request.Url); fileName = uri.AbsolutePath; // if url is blocked /*if (!myForm.IsURLOk(request.Url)) { * // return true so it does not open up * return true; * }*/ // if url is browser file if (uri.Host == "browser") { fileName = appPath + fileName; if (File.Exists(fileName)) { Task.Factory.StartNew(() => { using (callback) { //var bytes = Encoding.UTF8.GetBytes(resource); //stream = new MemoryStream(bytes); FileStream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); mimeType = ResourceHandler.GetMimeType(Path.GetExtension(fileName)); stream = fStream; callback.Continue(); } }); return(true); } } // by default reject callback.Dispose(); return(false); }
// // Summary: // Open the response stream. - To handle the request immediately set handleRequest // to true and return true. - To decide at a later time set handleRequest to false, // return true, and execute callback to continue or cancel the request. - To cancel // the request immediately set handleRequest to true and return false. This method // will be called in sequence but not from a dedicated thread. For backwards compatibility // set handleRequest to false and return false and the CefSharp.IResourceHandler.ProcessRequest(CefSharp.IRequest,CefSharp.ICallback) // method will be called. // // Parameters: // request: // request // // handleRequest: // see main summary // // callback: // callback // // Returns: // see main summary public bool Open(IRequest request, out bool handleRequest, ICallback callback) { Console.WriteLine("Open >> " + request.Url); uri = new Uri(request.Url); fileName = uri.AbsolutePath; // if url is blocked /*if (...request.Url....) { * * // cancel the request - set handleRequest to true and return false * handleRequest = true; * return false; * }*/ // if url is browser file if (uri.Host == "storage") { fileName = appPath + uri.Host + fileName; Console.WriteLine(File.Exists(fileName) + " - " + fileName); if (File.Exists(fileName)) { Task.Factory.StartNew(() => { using (callback) { FileStream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); mimeType = ResourceHandler.GetMimeType(Path.GetExtension(fileName)); stream = fStream; callback.Continue(); } }); // handle the request at a later time handleRequest = false; return(true); } } // if url is request for icon of another file if (uri.Host == "fileicon") { Task.Factory.StartNew(() => { using (callback) { stream = FileIconUtils.GetFileIcon(fileName, FileIconSize.Large); mimeType = ResourceHandler.GetMimeType(".png"); callback.Continue(); } }); // handle the request at a later time handleRequest = false; return(true); } // by default reject callback.Dispose(); // cancel the request - set handleRequest to true and return false handleRequest = true; return(false); }
public BrowserTabView() { InitializeComponent(); browser.RequestHandler = new RequestHandler(); //See https://github.com/cefsharp/CefSharp/issues/2246 for details on the two different binding options if (CefSharpSettings.LegacyJavascriptBindingEnabled) { browser.RegisterJsObject("bound", new BoundObject(), options: BindingOptions.DefaultBinder); } else { //Register the new way browser.JavascriptObjectRepository.Register("bound", new BoundObject(), isAsync: false, options: BindingOptions.DefaultBinder); } var bindingOptions = new BindingOptions() { Binder = BindingOptions.DefaultBinder.Binder, MethodInterceptor = new MethodInterceptorLogger() // intercept .net methods calls from js and log it }; //See https://github.com/cefsharp/CefSharp/issues/2246 for details on the two different binding options if (CefSharpSettings.LegacyJavascriptBindingEnabled) { browser.RegisterAsyncJsObject("boundAsync", new AsyncBoundObject(), options: bindingOptions); } else { //Register the new way browser.JavascriptObjectRepository.Register("boundAsync", new AsyncBoundObject(), isAsync: true, options: bindingOptions); } //If you call CefSharp.BindObjectAsync in javascript and pass in the name of an object which is not yet //bound, then ResolveObject will be called, you can then register it browser.JavascriptObjectRepository.ResolveObject += (sender, e) => { var repo = e.ObjectRepository; if (e.ObjectName == "boundAsync2") { repo.Register("boundAsync2", new AsyncBoundObject(), isAsync: true, options: bindingOptions); } }; browser.JavascriptObjectRepository.ObjectBoundInJavascript += (sender, e) => { var name = e.ObjectName; }; browser.DisplayHandler = new DisplayHandler(); browser.LifeSpanHandler = new LifespanHandler(); browser.MenuHandler = new MenuHandler(); browser.GeolocationHandler = new GeolocationHandler(); var downloadHandler = new DownloadHandler(); downloadHandler.OnBeforeDownloadFired += OnBeforeDownloadFired; downloadHandler.OnDownloadUpdatedFired += OnDownloadUpdatedFired; browser.DownloadHandler = downloadHandler; //Read an embedded bitmap into a memory stream then register it as a resource you can then load custom://cefsharp/images/beach.jpg var beachImageStream = new MemoryStream(); CefSharp.Example.Properties.Resources.beach.Save(beachImageStream, System.Drawing.Imaging.ImageFormat.Jpeg); browser.RegisterResourceHandler(CefExample.BaseUrl + "/images/beach.jpg", beachImageStream, ResourceHandler.GetMimeType(".jpg")); var dragHandler = new DragHandler(); dragHandler.RegionsChanged += OnDragHandlerRegionsChanged; browser.DragHandler = dragHandler; //browser.ResourceHandlerFactory = new InMemorySchemeAndResourceHandlerFactory(); //You can specify a custom RequestContext to share settings amount groups of ChromiumWebBrowsers //Also this is now the only way to access OnBeforePluginLoad - need to implement IRequestContextHandler //browser.RequestContext = new RequestContext(new RequestContextHandler()); //NOTE - This is very important for this example as the default page will not load otherwise //browser.RequestContext.RegisterSchemeHandlerFactory(CefSharpSchemeHandlerFactory.SchemeName, null, new CefSharpSchemeHandlerFactory()); //You can start setting preferences on a RequestContext that you created straight away, still needs to be called on the CEF UI thread. //Cef.UIThreadTaskFactory.StartNew(delegate //{ // string errorMessage; // //Use this to check that settings preferences are working in your code // var success = browser.RequestContext.SetPreference("webkit.webprefs.minimum_font_size", 24, out errorMessage); //}); browser.RenderProcessMessageHandler = new RenderProcessMessageHandler(); browser.LoadError += (sender, args) => { // Don't display an error for downloaded files. if (args.ErrorCode == CefErrorCode.Aborted) { return; } // Don't display an error for external protocols that we allow the OS to // handle. See OnProtocolExecution(). //if (args.ErrorCode == CefErrorCode.UnknownUrlScheme) //{ // var url = args.Frame.Url; // if (url.StartsWith("spotify:")) // { // return; // } //} // Display a load error message. var errorBody = string.Format("<html><body bgcolor=\"white\"><h2>Failed to load URL {0} with error {1} ({2}).</h2></body></html>", args.FailedUrl, args.ErrorText, args.ErrorCode); args.Frame.LoadStringForUrl(errorBody, args.FailedUrl); }; CefExample.RegisterTestResources(browser); }
public BrowserTabView() { InitializeComponent(); //browser.BrowserSettings.BackgroundColor = Cef.ColorSetARGB(0, 255, 255, 255); browser.RequestHandler = new ExampleRequestHandler(); var bindingOptions = new BindingOptions() { Binder = BindingOptions.DefaultBinder.Binder, MethodInterceptor = new MethodInterceptorLogger() // intercept .net methods calls from js and log it }; //To use the ResolveObject below and bind an object with isAsync:false we must set CefSharpSettings.WcfEnabled = true before //the browser is initialized. CefSharpSettings.WcfEnabled = true; //If you call CefSharp.BindObjectAsync in javascript and pass in the name of an object which is not yet //bound, then ResolveObject will be called, you can then register it browser.JavascriptObjectRepository.ResolveObject += (sender, e) => { var repo = e.ObjectRepository; if (e.ObjectName == "boundAsync2") { repo.Register("boundAsync2", new AsyncBoundObject(), isAsync: true, options: bindingOptions); } else if (e.ObjectName == "bound") { browser.JavascriptObjectRepository.Register("bound", new BoundObject(), isAsync: false, options: BindingOptions.DefaultBinder); } else if (e.ObjectName == "boundAsync") { browser.JavascriptObjectRepository.Register("boundAsync", new AsyncBoundObject(), isAsync: true, options: bindingOptions); } }; browser.JavascriptObjectRepository.ObjectBoundInJavascript += (sender, e) => { var name = e.ObjectName; Debug.WriteLine($"Object {e.ObjectName} was bound successfully."); }; browser.DisplayHandler = new DisplayHandler(); //This LifeSpanHandler implementaion demos hosting a popup in a ChromiumWebBrowser //instance, it's still considered Experimental //browser.LifeSpanHandler = new ExperimentalLifespanHandler(); browser.MenuHandler = new MenuHandler(); browser.AccessibilityHandler = new AccessibilityHandler(); var downloadHandler = new DownloadHandler(); downloadHandler.OnBeforeDownloadFired += OnBeforeDownloadFired; downloadHandler.OnDownloadUpdatedFired += OnDownloadUpdatedFired; browser.DownloadHandler = downloadHandler; //Read an embedded bitmap into a memory stream then register it as a resource you can then load custom://cefsharp/images/beach.jpg var beachImageStream = new MemoryStream(); CefSharp.Example.Properties.Resources.beach.Save(beachImageStream, System.Drawing.Imaging.ImageFormat.Jpeg); browser.RegisterResourceHandler(CefExample.BaseUrl + "/images/beach.jpg", beachImageStream, ResourceHandler.GetMimeType(".jpg")); var dragHandler = new DragHandler(); dragHandler.RegionsChanged += OnDragHandlerRegionsChanged; browser.DragHandler = dragHandler; //browser.ResourceHandlerFactory = new InMemorySchemeAndResourceHandlerFactory(); //You can specify a custom RequestContext to share settings amount groups of ChromiumWebBrowsers //Also this is now the only way to access OnBeforePluginLoad - need to implement IRequestContextHandler //browser.RequestContext = new RequestContext(new RequestContextHandler()); //NOTE - This is very important for this example as the default page will not load otherwise //browser.RequestContext.RegisterSchemeHandlerFactory(CefSharpSchemeHandlerFactory.SchemeName, null, new CefSharpSchemeHandlerFactory()); //browser.RequestContext.RegisterSchemeHandlerFactory("https", "cefsharp.example", new CefSharpSchemeHandlerFactory()); //You can start setting preferences on a RequestContext that you created straight away, still needs to be called on the CEF UI thread. //Cef.UIThreadTaskFactory.StartNew(delegate //{ // string errorMessage; // //Use this to check that settings preferences are working in your code // var success = browser.RequestContext.SetPreference("webkit.webprefs.minimum_font_size", 24, out errorMessage); //}); browser.RenderProcessMessageHandler = new RenderProcessMessageHandler(); browser.LoadError += (sender, args) => { // Don't display an error for downloaded files. if (args.ErrorCode == CefErrorCode.Aborted) { return; } //Don't display an error for external protocols that we allow the OS to //handle in OnProtocolExecution(). if (args.ErrorCode == CefErrorCode.UnknownUrlScheme && args.Frame.Url.StartsWith("mailto")) { return; } // Display a load error message. var errorBody = string.Format("<html><body bgcolor=\"white\"><h2>Failed to load URL {0} with error {1} ({2}).</h2></body></html>", args.FailedUrl, args.ErrorText, args.ErrorCode); args.Frame.LoadHtml(errorBody, base64Encode: true); }; CefExample.RegisterTestResources(browser); browser.JavascriptMessageReceived += OnBrowserJavascriptMessageReceived; }
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { //Notes: // - The 'host' portion is entirely ignored by this scheme handler. // - If you register a ISchemeHandlerFactory for http/https schemes you should also specify a domain name // - Avoid doing lots of processing in this method as it will affect performance. // - Use the Default ResourceHandler implementation var uri = new Uri(request.Url); var fileName = uri.AbsolutePath; string resource; if (ResourceDictionary.TryGetValue(fileName, out resource) && !string.IsNullOrEmpty(resource)) { var fileExtension = Path.GetExtension(fileName); return(ResourceHandler.FromString(resource, includePreamble: true, mimeType: ResourceHandler.GetMimeType(fileExtension))); } //Load a file directly from disk, then cache it if (File.Exists($"html{fileName}")) { var text = File.ReadAllText($"html{fileName}"); var fileExtension = Path.GetExtension(fileName); ResourceDictionary.Add(fileName, text); return(ResourceHandler.FromString(text, includePreamble: true, mimeType: ResourceHandler.GetMimeType(fileExtension))); } return(null); }
bool IResourceHandler.ProcessRequest(IRequest request, ICallback callback) { // The 'host' portion is entirely ignored by this scheme handler. var uri = new Uri(request.Url); var fileName = uri.AbsolutePath; if (string.Equals(fileName, "/PostDataTest.html", StringComparison.OrdinalIgnoreCase)) { var postDataElement = request.PostData.Elements.FirstOrDefault(); var resourceHandler = (ResourceHandler)ResourceHandler.FromString("Post Data: " + (postDataElement == null ? "null" : postDataElement.GetBody())); stream = (MemoryStream)resourceHandler.Stream; mimeType = "text/html"; callback.Continue(); return(true); } if (string.Equals(fileName, "/PostDataAjaxTest.html", StringComparison.OrdinalIgnoreCase)) { var postData = request.PostData; if (postData == null) { var resourceHandler = (ResourceHandler)ResourceHandler.FromString("Post Data: null"); stream = (MemoryStream)resourceHandler.Stream; mimeType = "text/html"; callback.Continue(); } else { var postDataElement = postData.Elements.FirstOrDefault(); var resourceHandler = (ResourceHandler)ResourceHandler.FromString("Post Data: " + (postDataElement == null ? "null" : postDataElement.GetBody())); stream = (MemoryStream)resourceHandler.Stream; mimeType = "text/html"; callback.Continue(); } return(true); } if (string.Equals(fileName, "/EmptyResponseFilterTest.html", StringComparison.OrdinalIgnoreCase)) { stream = null; mimeType = "text/html"; callback.Continue(); return(true); } string resource; if (ResourceDictionary.TryGetValue(fileName, out resource) && !string.IsNullOrEmpty(resource)) { Task.Run(() => { using (callback) { var bytes = Encoding.UTF8.GetBytes(resource); stream = new MemoryStream(bytes); var fileExtension = Path.GetExtension(fileName); mimeType = ResourceHandler.GetMimeType(fileExtension); callback.Continue(); } }); return(true); } else { callback.Dispose(); } return(false); }
public BrowserTabView() { InitializeComponent(); browser.RequestHandler = new RequestHandler(); browser.RegisterJsObject("bound", new BoundObject(), BindingOptions.DefaultBinder); browser.RegisterAsyncJsObject("boundAsync", new AsyncBoundObject()); // Enable touch scrolling - once properly tested this will likely become the default //browser.IsManipulationEnabled = true; browser.LifeSpanHandler = new LifespanHandler(); browser.MenuHandler = new MenuHandler(); browser.GeolocationHandler = new GeolocationHandler(); var downloadHandler = new DownloadHandler(); downloadHandler.OnBeforeDownloadFired += OnBeforeDownloadFired; downloadHandler.OnDownloadUpdatedFired += OnDownloadUpdatedFired; browser.DownloadHandler = downloadHandler; //Read an embedded bitmap into a memory stream then register it as a resource you can then load custom://cefsharp/images/beach.jpg var beachImageStream = new MemoryStream(); CefSharp.Example.Properties.Resources.beach.Save(beachImageStream, System.Drawing.Imaging.ImageFormat.Jpeg); browser.RegisterResourceHandler(CefExample.BaseUrl + "/images/beach.jpg", beachImageStream, ResourceHandler.GetMimeType(".jpg")); var dragHandler = new DragHandler(); dragHandler.RegionsChanged += OnDragHandlerRegionsChanged; browser.DragHandler = dragHandler; //browser.ResourceHandlerFactory = new InMemorySchemeAndResourceHandlerFactory(); //You can specify a custom RequestContext to share settings amount groups of ChromiumWebBrowsers //Also this is now the only way to access OnBeforePluginLoad - need to implement IRequestContextHandler //browser.RequestContext = new RequestContext(new RequestContextHandler()); //NOTE - This is very important for this example as the default page will not load otherwise //browser.RequestContext.RegisterSchemeHandlerFactory(CefSharpSchemeHandlerFactory.SchemeName, null, new CefSharpSchemeHandlerFactory()); //You can start setting preferences on a RequestContext that you created straight away, still needs to be called on the CEF UI thread. //Cef.UIThreadTaskFactory.StartNew(delegate //{ // string errorMessage; // //Use this to check that settings preferences are working in your code // var success = browser.RequestContext.SetPreference("webkit.webprefs.minimum_font_size", 24, out errorMessage); //}); browser.RenderProcessMessageHandler = new RenderProcessMessageHandler(); browser.LoadError += (sender, args) => { // Don't display an error for downloaded files. if (args.ErrorCode == CefErrorCode.Aborted) { return; } // Don't display an error for external protocols that we allow the OS to // handle. See OnProtocolExecution(). //if (args.ErrorCode == CefErrorCode.UnknownUrlScheme) //{ // var url = args.Frame.Url; // if (url.StartsWith("spotify:")) // { // return; // } //} // Display a load error message. var errorBody = string.Format("<html><body bgcolor=\"white\"><h2>Failed to load URL {0} with error {1} ({2}).</h2></body></html>", args.FailedUrl, args.ErrorText, args.ErrorCode); args.Frame.LoadStringForUrl(errorBody, args.FailedUrl); }; CefExample.RegisterTestResources(browser); }
private string GetMimeType(string fileName) { return(ResourceHandler.GetMimeType(System.IO.Path.GetExtension(fileName))); }
public static string GetMimeType(string resourceName) { return(ResourceHandler.GetMimeType(Path.GetExtension(resourceName))); }
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))); }
private void DownloadChapter(Dictionary <int, string> Chapters, int ID, IHost Host, ComicInfo Info) { string Name = DataTools.GetRawName(Chapters[ID], FileNameMode: true); StatusBar.SecondLabelText = $"{Info.Title} - {string.Format(CurrentLanguage.ChapterName, Name)}"; Status = CurrentLanguage.Loading; int KIndex = Chapters.IndexOfKey(ID); string LName = null; string LastChapterPah = null; if (KIndex + 1 < Chapters.Keys.Count) { LName = DataTools.GetRawName(Chapters.Values.ElementAt(KIndex + 1), FileNameMode: true); } string NName = null; string NextChapterPath = null; if (KIndex > 0) { NName = DataTools.GetRawName(Chapters.Values.ElementAt(KIndex - 1), FileNameMode: true); } string Title = DataTools.GetRawName(Info.Title.Trim(), FileNameMode: true); ChapterTools.MatchLibraryPath(ref Title, Settings.LibraryPath, CurrentInfo.Url, (ReplaceMode)Settings.ReplaceMode, CurrentLanguage); RefreshCoverLink(Title); string TitleDir = Path.Combine(Settings.LibraryPath, Title); if (!Directory.Exists(TitleDir)) { Directory.CreateDirectory(TitleDir); RefreshLibrary(); } if (LName != null) { ChapterTools.GetChapterPath(Languages, CurrentLanguage, TitleDir, LName, out LastChapterPah, false); } ChapterTools.GetChapterPath(Languages, CurrentLanguage, TitleDir, Name, out string ChapterPath, false); if (NName != null) { ChapterTools.GetChapterPath(Languages, CurrentLanguage, TitleDir, NName, out NextChapterPath, false); } string AbsoluteChapterPath = Path.Combine(TitleDir, ChapterPath); if (Settings.SkipDownloaded && File.Exists(AbsoluteChapterPath.TrimEnd('\\', '/') + ".html")) { return; } int PageCount = 1; if (Info.ContentType == ContentType.Comic) { PageCount = Host.GetChapterPageCount(ID); if (Directory.Exists(AbsoluteChapterPath) && Directory.GetFiles(AbsoluteChapterPath, "*").Length < PageCount) { Directory.Delete(AbsoluteChapterPath, true); } if (Settings.SkipDownloaded && Directory.Exists(AbsoluteChapterPath)) { var Pages = (from x in Directory.GetFiles(AbsoluteChapterPath) select Path.GetFileName(x)).ToArray(); ChapterTools.GenerateComicReader(CurrentLanguage, Pages, LastChapterPah, NextChapterPath, TitleDir, ChapterPath, Name); string OnlineData = string.Format(Properties.Resources.UrlFile, Info.Url.AbsoluteUri); File.WriteAllText(Path.Combine(TitleDir, "Online.url"), OnlineData); return; } } if (Info.ContentType == ContentType.Novel) { ChapterPath = Path.Combine(AbsoluteChapterPath, string.Format(CurrentLanguage.ChapterName, Name) + ".epub"); if (Settings.SkipDownloaded && File.Exists(ChapterPath)) { return; } } if (!Directory.Exists(AbsoluteChapterPath)) { Directory.CreateDirectory(AbsoluteChapterPath); } string UrlData = string.Format(Properties.Resources.UrlFile, Info.Url.AbsoluteUri); File.WriteAllText(Path.Combine(TitleDir, "Online.url"), UrlData); switch (Info.ContentType) { case ContentType.Comic: var Decoder = Host.GetDecoder(); List <string> Pages = new List <string>(); foreach (var Data in Host.DownloadPages(ID).CatchExceptions()) { Status = string.Format(CurrentLanguage.Downloading, Pages.Count + 1, PageCount); Application.DoEvents(); bool IsWebP = Data.Length > 12 && BitConverter.ToUInt32(Data, 8) == 0x50424557; try { #if NOASYNCSAVE string PageName = $"{Pages.Count:D3}.png"; string PagePath = Path.Combine(TitleDir, ChapterPath, PageName); Page OutPage = new Page(); OutPage.Data = Data; if ((SaveAs)Settings.SaveAs != SaveAs.RAW) { using (Bitmap Result = Decoder.Decode(Data)) { PageName = $"{Pages.Count:D3}.{GetExtension(Result, out ImageFormat Format)}"; PagePath = OutPage.Path = Path.Combine(TitleDir, ChapterPath, PageName); if (Result.GetImageExtension() == "png" && Settings.APNGBypass) { var OutData = BypassAPNG(Data); OutPage.Data = OutData; } else { using (MemoryStream tmp = new MemoryStream()) { Result.Save(tmp, Format); OutPage.Data = tmp.ToArray(); } } } } if (Settings.ImageClipping) { PostProcessQueue.Enqueue(OutPage); } else { File.WriteAllBytes(OutPage.Path, OutPage.Data); } while (PostProcessQueue.Count > 0) { ThreadTools.Wait(1000, true); } #else string PageName = $"{Pages.Count:D3}.{(IsWebP ? "webp" : "png")}"; string PagePath = Path.Combine(TitleDir, ChapterPath, PageName); Page OutPage = new Page(); OutPage.Data = Data; if ((SaveAs)Settings.SaveAs != SaveAs.RAW) { byte[] ModData = null; if (IsWebP) { ModData = DecodeWebP(Data); } using (MemoryStream Buffer = new MemoryStream()) using (Bitmap Result = Decoder.Decode(ModData ?? Data)) { PageName = $"{Pages.Count:D3}.{GetExtension(Result, out ImageFormat Format)}"; PagePath = Path.Combine(TitleDir, ChapterPath, PageName); if (Result.GetImageExtension() == "png" && Settings.APNGBypass) { using (MemoryStream OutBuffer = new MemoryStream(BypassAPNG(ModData ?? Data))) using (Bitmap Img = new Bitmap(OutBuffer)) { Img.Save(Buffer, Format); OutPage.Data = Buffer.ToArray(); } } else { Result.Save(Buffer, Format); OutPage.Data = Buffer.ToArray(); } } } OutPage.Path = PagePath; if (PostProcessQueue.Count > 5) { const ulong MinMemory = 400000000; while (AvailablePhysicalMemory < MinMemory && PostProcessQueue.Count > 0 || (Settings.MaxPagesBuffer != 0 && PostProcessQueue.Count >= Settings.MaxPagesBuffer)) { ThreadTools.Wait(1000, true); } } PostProcessQueue.Enqueue(OutPage); #endif Pages.Add(PageName); } catch (Exception ex) { if (Program.Debug) { throw; } Console.Error.WriteLine(ex.ToString()); } } if (Settings.ReaderGenerator) { ChapterTools.GenerateComicReader(CurrentLanguage, Pages.ToArray(), LastChapterPah, NextChapterPath, TitleDir, ChapterPath, Name); ChapterTools.GenerateReaderIndex(Languages, CurrentLanguage, Info, TitleDir, Name); } break; case ContentType.Novel: var Chapter = Host.DownloadChapter(ID); AsyncContext.Run(async() => { using (var Epub = await EPubWriter.CreateWriterAsync(File.Create(ChapterPath), Info.Title ?? "Untitled", Chapter.Author ?? "Anon", Chapter.URL ?? "None")) { Chapter.HTML.RemoveNodes("//script"); Chapter.HTML.RemoveNodes("//iframe"); foreach (var Node in Chapter.HTML.DocumentNode.DescendantsAndSelf()) { if (Node.Name == "img" && Node.GetAttributeValue("src", string.Empty) != string.Empty) { string Src = Node.GetAttributeValue("src", string.Empty); string RName = Path.GetFileName(Src.Substring(null, "?", IgnoreMissmatch: true)); string Mime = ResourceHandler.GetMimeType(Path.GetExtension(RName)); if (Node.GetAttributeValue("type", string.Empty) != string.Empty) { Mime = Node.GetAttributeValue("type", string.Empty); } Uri Link = new Uri(Info.Url, Src); if (string.IsNullOrWhiteSpace(RName)) { continue; } byte[] Buffer = await Link.TryDownloadAsync(); if (Buffer == null) { continue; } await Epub.AddResourceAsync(RName, Mime, Buffer); Node.SetAttributeValue("src", RName); } if (Node.Name == "link" && Node.GetAttributeValue("rel", string.Empty) == "stylesheet" && Node.GetAttributeValue("href", string.Empty) != string.Empty) { string Src = Node.GetAttributeValue("href", string.Empty); string RName = Path.GetFileName(Src.Substring(null, "?", IgnoreMissmatch: true)); string Mime = ResourceHandler.GetMimeType(Path.GetExtension(RName)); if (Node.GetAttributeValue("type", string.Empty) != string.Empty) { Mime = Node.GetAttributeValue("type", string.Empty); } Uri Link = new Uri(Info.Url, Src); if (string.IsNullOrWhiteSpace(RName)) { continue; } byte[] Buffer = await Link.TryDownloadAsync(); if (Buffer == null) { continue; } await Epub.AddResourceAsync(RName, Mime, Buffer); Node.SetAttributeValue("href", RName); } } Epub.Publisher = lblTitle.Text; await Epub.AddChapterAsync("chapter.xhtml", Chapter.Title, Chapter.HTML.ToHTML()); await Epub.WriteEndOfPackageAsync(); } }); break; default: throw new Exception("Invalid Content Type"); } }