예제 #1
0
        public override CefReturnValue ProcessRequestAsync(IRequest request, ICallback callback)
        {
            var    names        = typeof(SkinView3D.Class).Assembly.GetManifestResourceNames();
            Uri    u            = new Uri(request.Url);
            string resourceName = string.Format("{0}{1}", u.Authority, u.AbsolutePath).ToLower();
            string resourcePath = @"/SkinView3D;component/" + resourceName;

            var  assembly           = typeof(SkinView3D.Class).Assembly;
            var  rm                 = new ResourceManager(assembly.GetName().Name + ".g", assembly);
            var  resources          = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true);
            var  resourceDictionary = resources.Cast <DictionaryEntry>().ToDictionary(r => r.Key.ToString(), r => r.Value.ToString());
            bool validResource      = resourceDictionary.ContainsKey(resourceName);

            if (validResource)
            {
                Task.Run(() =>
                {
                    using (callback)
                    {
                        try
                        {
                            StreamResourceInfo sri = Application.GetResourceStream(new Uri(resourcePath, UriKind.Relative));

                            if (sri != null)
                            {
                                Stream stream   = sri.Stream;
                                string mimeType = sri.ContentType;

                                // Reset the stream position to 0 so the stream can be copied into the underlying unmanaged buffer
                                stream.Position = 0;
                                // Populate the response values - No longer need to implement GetResponseHeaders (unless you need to perform a redirect)
                                ResponseLength = stream.Length;
                                MimeType       = mimeType;
                                StatusCode     = (int)HttpStatusCode.OK;
                                Stream         = stream;

                                callback.Continue();
                            }
                            else
                            {
                                callback.Cancel();
                            }
                        }
                        catch (Exception ex)
                        {
                            callback.Cancel();
                            Program.LogConsoleLine(ex);
                        }
                    }
                });
            }
            else
            {
                callback.Cancel();
            }

            rm.ReleaseAllResources();

            return(CefReturnValue.ContinueAsync);
        }
예제 #2
0
        public override CefReturnValue ProcessRequestAsync(IRequest request, ICallback callback)
        {
            var uri = new Uri(request.Url);

            var file = $"{uri.Host}:{uri.LocalPath}";

            Task.Run(() =>
            {
                using (callback)
                {
                    if (!File.Exists(file))
                    {
                        callback.Cancel();
                        return;
                    }

                    byte[] bytes = File.ReadAllBytes(file);

                    var stream = new MemoryStream(bytes)
                    {
                        Position = 0
                    };
                    ResponseLength = stream.Length;

                    var fileExtension = Path.GetExtension(file);
                    MimeType          = GetMimeType(fileExtension);
                    StatusCode        = (int)HttpStatusCode.OK;
                    Stream            = stream;

                    callback.Continue();
                }
            });

            return(CefReturnValue.ContinueAsync);
        }
예제 #3
0
        public override CefReturnValue ProcessRequestAsync(IRequest request, ICallback callback)
        {
            Task.Run(() =>
            {
                using (callback)
                {
                    try
                    {
                        string url = request.Url;
                        var uri    = new Uri(url);

                        //Get the absolute path and remove the leading slash
                        var asbolutePath = string.Format("{0}:\\", uri.Authority) + uri.AbsolutePath.Substring(1);

                        var filePath = WebUtility.UrlDecode(Path.GetFullPath(asbolutePath));

                        if (File.Exists(filePath))
                        {
                            Stream stream   = File.OpenRead(filePath);
                            string mimeType = MimeMapping.GetMimeMapping(filePath);

                            // Reset the stream position to 0 so the stream can be copied into the underlying unmanaged buffer
                            stream.Position = 0;
                            // Populate the response values - No longer need to implement GetResponseHeaders (unless you need to perform a redirect)
                            ResponseLength = stream.Length;
                            MimeType       = mimeType;
                            StatusCode     = (int)HttpStatusCode.OK;
                            Stream         = stream;

                            callback.Continue();
                        }
                        else
                        {
                            callback.Cancel();
                        }
                    }
                    catch (Exception ex)
                    {
                        callback.Cancel();
                        System.Diagnostics.Debug.WriteLine(ex);
                    }
                }
            });

            return(CefReturnValue.ContinueAsync);
        }
        /// <summary>
        /// The process request async.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public override CefReturnValue ProcessRequestAsync(IRequest request, ICallback callback)
        {
            var uri      = new Uri(request.Url);
            var fileName = uri.AbsolutePath;

            var u    = new Uri(request.Url);
            var file = u.Authority + u.AbsolutePath;

            _fileInfo = new FileInfo(file);
            // Check if file exists
            if (!_fileInfo.Exists)
            {
                _chromelyResource = _chromelyErrorHandler.HandleError(_fileInfo);
                callback.Continue();
            }
            // Check if file exists but empty
            else if (_fileInfo.Length == 0)
            {
                _chromelyResource = _chromelyErrorHandler.HandleError(_fileInfo);
                callback.Continue();
            }
            else
            {
                Task.Run(() =>
                {
                    using (callback)
                    {
                        _chromelyResource.Content  = null;
                        _chromelyResource.MimeType = "text/html";

                        try
                        {
                            byte[] fileBytes          = File.ReadAllBytes(file);
                            _chromelyResource.Content = new MemoryStream(fileBytes);

                            string extension           = Path.GetExtension(file);
                            _chromelyResource.MimeType = MimeMapper.GetMimeType(extension);
                        }
                        catch (Exception exception)
                        {
                            _chromelyResource = _chromelyErrorHandler.HandleError(_fileInfo, exception);
                        }

                        if (_chromelyResource.Content == null)
                        {
                            callback.Cancel();
                        }
                        else
                        {
                            SetResponseInfoOnSuccess();
                            callback.Continue();
                        }
                    }
                });
            }

            return(CefReturnValue.ContinueAsync);
        }
예제 #5
0
        /// <summary>
        /// The process request async.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public override CefReturnValue ProcessRequestAsync(IRequest request, ICallback callback)
        {
            var u = new Uri(request.Url);
            var fileAbsolutePath = u.AbsolutePath;
            var file             = u.Authority + fileAbsolutePath;

            _fileInfo = new FileInfo(file);
            // Check if file exists
            if (!_fileInfo.Exists)
            {
                _chromelyResource = _chromelyErrorHandler.HandleError(_fileInfo);
                callback.Continue();
            }
            // Check if file exists but empty
            else if (_fileInfo.Length == 0)
            {
                _chromelyResource = _chromelyErrorHandler.HandleError(_fileInfo);
                callback.Continue();
            }
            else
            {
                Task.Run(() =>
                {
                    using (callback)
                    {
                        _chromelyResource.Content  = null;
                        _chromelyResource.MimeType = "text/html";

                        try
                        {
                            if (!ProcessAssmblyEmbeddedFile(request.Url, file, fileAbsolutePath))
                            {
                                ProcessLocalFile(file);
                            }
                        }
                        catch (Exception exception)
                        {
                            _chromelyResource = _chromelyErrorHandler.HandleError(_fileInfo, exception);
                        }

                        if (_chromelyResource.Content == null)
                        {
                            callback.Cancel();
                        }
                        else
                        {
                            SetResponseInfoOnSuccess();
                            callback.Continue();
                        }
                    }
                });
            }

            return(CefReturnValue.ContinueAsync);
        }
예제 #6
0
        /// <summary>
        /// The process request async.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public override CefReturnValue ProcessRequestAsync(IRequest request, ICallback callback)
        {
            if (!this.PrepareRequest(request))
            {
                return(CefReturnValue.Cancel);
            }

            _cancellationTokenSource = new CancellationTokenSource();
            _dataStream = null;

            Task.Run(async() =>
            {
                using (callback)
                {
                    try
                    {
                        if (await LoadResourceData(_cancellationTokenSource.Token))
                        {
                            _dataStream = await GetResourceDataStream(_cancellationTokenSource.Token);
                        }
                    }
                    catch (TaskCanceledException)
                    {
                        Logger.Instance.Log.LogInformation("The request was canceled.");
                    }
                    catch (Exception ex) when(ex.Message == "The request was aborted: The request was canceled.")
                    {
                        Logger.Instance.Log.LogInformation("The request was canceled.");
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Log.LogError(ex, "Exception thrown while loading resource");
                    }

                    if (_dataStream == null)
                    {
                        callback.Cancel();
                    }
                    else
                    {
                        SetResponseInfoOnSuccess();
                        callback.Continue();
                    }
                }
            });

            return(CefReturnValue.ContinueAsync);
        }
예제 #7
0
        public override bool ProcessRequestAsync(IRequest request, ICallback callback)
        {
            var domain = GlobalConfig.Domain.EmbeddedName;

            if (!request.Url.StartsWith(domain, StringComparison.OrdinalIgnoreCase))
            {
                return(true);
            }

            Task.Run(() =>
            {
                // In this task you can perform your time consuming operations, e.g query a database
                // NOTE: We suggest that you wrap callbacks in a using statemnt so that they're disposed
                // even if there is an exception as they wrap an unmanaged response which will cause memory
                // leaks if not freed
                using (callback)
                {
                    var url        = request.Url.Replace(domain, string.Empty);
                    var requestRes = this.GetEmbeddedResName(url.ToAppPath(true));
                    var stream     = CurrentAssembly.GetManifestResourceStream(requestRes);
                    if (stream == null)
                    {
                        callback.Cancel();
                    }
                    else
                    {
                        //Reset the stream position to 0 so the stream can be copied into the underlying unmanaged buffer
                        stream.Position = 0;
                        //Populate the response values - No longer need to implement GetResponseHeaders (unless you need to perform a redirect)
                        ResponseLength = stream.Length;
                        MimeType       = GetMimeType(Path.GetExtension(requestRes));
                        StatusCode     = (int)HttpStatusCode.OK;
                        Stream?.Dispose();
                        Stream = stream;

                        callback.Continue();
                    }
                }
            }).ConfigureAwait(false);

            return(true);
        }
예제 #8
0
            public override bool ProcessRequestAsync(IRequest request, ICallback callback)
            {
                Task.Run(() =>
                {
                    var uri = new Uri(request.Url);

                    try
                    {
                        var resource   = Application.GetResourceStream(new Uri(uri.AbsolutePath, UriKind.Relative));
                        MimeType       = resource.ContentType;
                        StatusCode     = (int)(HttpStatusCode.OK);
                        Stream         = resource.Stream;
                        ResponseLength = Stream.Length;

                        callback.Continue();
                    }
                    catch (IOException)
                    {
                        callback.Cancel();
                    }
                });

                return(true);
            }
예제 #9
0
        public bool ProcessRequest(IRequest request, ICallback callback)
        {
            try
            {
                // Request start/finish is logged already by Asp.Net Core, so we'll only log at debug level
                _logger.LogDebug(LoggerEventIds.RequestStarting, "Request starting {0} '{1}'", request.Method, request.Url);

                var url = new Uri(request.Url);
                _requestUri = url;

                var internalRequest = new PositronRequest
                {
                    Protocol    = "HTTP/1.1",
                    Method      = request.Method,
                    Path        = Uri.UnescapeDataString(url.AbsolutePath),
                    QueryString = url.Query,
                    Scheme      = url.Scheme,
                    Headers     = new CefHeaderDictionary(request.Headers)
                };

                if (!internalRequest.Headers.ContainsKey("Host"))
                {
                    // We need to pass the Host header to ensure correct URL in logging
                    internalRequest.Headers.Add("Host", new StringValues("positron"));
                }

                if (request.PostData != null && request.PostData.Elements.Any())
                {
                    internalRequest.Body = new MemoryStream(request.PostData.Elements.First().Bytes);
                }

                Task.Run(() =>
                {
                    var processor = _webHost.ServerFeatures.Get <IInternalHttpRequestFeature>();

                    // Do this in a task to ensure it doesn't execute synchronously on the ProcessRequest thread
                    processor.ProcessRequestAsync(internalRequest)
                    .ContinueWith(task =>
                    {
                        _logger.LogDebug(LoggerEventIds.RequestFinished, "Request finished {0} '{1}': {2}",
                                         internalRequest.Method, _requestUri, task.Result.StatusCode);

                        using (callback)
                        {
                            _response = task.Result;

                            callback.Continue();
                        }
                    }, TaskContinuationOptions.OnlyOnRanToCompletion)
                    .ContinueWith(task =>
                    {
                        _logger.LogError(LoggerEventIds.RequestError, task.Exception, "Error processing request '{0}'",
                                         _requestUri);

                        using (callback)
                        {
                            _response = null;

                            callback.Cancel();
                        }
                    }, TaskContinuationOptions.NotOnRanToCompletion)
                    .ContinueWith(task =>
                    {
                        internalRequest.Body?.Dispose();
                    });
                });

                return(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(LoggerEventIds.RequestError, ex, "Error processing request '{0}'", _requestUri);

                callback.Cancel();
                callback.Dispose();
                return(true);
            }
        }
        /// <summary>
        /// The process request async.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public override CefReturnValue ProcessRequestAsync(IRequest request, ICallback callback)
        {
            var uri = new Uri(request.Url);
            var fileName = uri.AbsolutePath;

            var u = new Uri(request.Url);
            var file = u.Authority + u.AbsolutePath;

            var fileInfo = new FileInfo(file);
            // Check if file exists 
            if (!fileInfo.Exists)
            {
                SetResponseInfoOnFailure((int)HttpStatusCode.NotFound, STATUSTEXT_FILENOTFOUND);
                callback.Continue();

                Logger.Instance.Log.LogWarning($"File: {file}: {StatusText}");
            }
            // Check if file exists but empty
            else if (fileInfo.Length == 0)
            {
                SetResponseInfoOnFailure((int)HttpStatusCode.BadRequest, STATUSTEXT_ZEROFILESIZE);
                callback.Continue();

                Logger.Instance.Log.LogWarning($"File: {file}: {StatusText}");
            }
            else  
            {
                Task.Run(() =>
                {
                    using (callback)
                    {
                        _stream = null;
                        _mimeType = "text/html";

                        try
                        {
                            byte[] fileBytes = File.ReadAllBytes(file);
                            _stream = new MemoryStream(fileBytes);

                            string extension = Path.GetExtension(file);
                            _mimeType = MimeMapper.GetMimeType(extension);
                        }
                        catch (Exception exception)
                        {
                            SetResponseInfoOnFailure((int)HttpStatusCode.BadRequest, STATUSTEXT_BADREQUEST);
                            Logger.Instance.Log.LogError(exception, exception.Message);
                        }

                        if (_stream == null)
                        {
                            callback.Cancel();
                        }
                        else
                        {
                            SetResponseInfoOnSuccess();
                            callback.Continue();
                        }
                    }
                });
            }

            return CefReturnValue.ContinueAsync;
        }
예제 #11
0
        /// <summary>
        /// The process request async.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public override CefReturnValue ProcessRequestAsync(IRequest request, ICallback callback)
        {
            var u = new Uri(request.Url);
            var fileAbsolutePath = u.AbsolutePath;
            var file             = u.Authority + fileAbsolutePath;

            var fileInfo = new FileInfo(file);

            // Check if file exists
            if (!fileInfo.Exists)
            {
                SetResponseInfoOnFailure((int)HttpStatusCode.NotFound, STATUSTEXT_FILENOTFOUND);
                callback.Continue();

                Logger.Instance.Log.LogWarning($"File: {file}: {StatusText}");
            }
            // Check if file exists but empty
            else if (fileInfo.Length == 0)
            {
                SetResponseInfoOnFailure((int)HttpStatusCode.BadRequest, STATUSTEXT_ZEROFILESIZE);
                callback.Continue();

                Logger.Instance.Log.LogWarning($"File: {file}: {StatusText}");
            }
            else
            {
                Task.Run(() =>
                {
                    using (callback)
                    {
                        _stream   = null;
                        _mimeType = "text/html";

                        try
                        {
                            if (!ProcessAssmblyEmbeddedFile(request.Url, file, fileAbsolutePath))
                            {
                                ProcessLocalFile(file);
                            }
                        }
                        catch (Exception exception)
                        {
                            SetResponseInfoOnFailure((int)HttpStatusCode.BadRequest, STATUSTEXT_BADREQUEST);
                            Logger.Instance.Log.LogError(exception, exception.Message);
                        }

                        if (_stream == null)
                        {
                            callback.Cancel();
                        }
                        else
                        {
                            SetResponseInfoOnSuccess();
                            callback.Continue();
                        }
                    }
                });
            }

            return(CefReturnValue.ContinueAsync);
        }
예제 #12
0
        //
        // Parameters:
        //   request:
        //     The request object.
        //
        //   callback:
        //
        //
        // 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.

        /// <summary>
        /// Begin processing the request by mapping it to a file on the file system.
        /// </summary>
        /// <param name="request">The request object.</param>
        /// <param name="callback">The callback used to Continue or Cancel the request (async).</param>
        /// <returns></returns>
        public override bool ProcessRequestAsync(IRequest request, ICallback callback)
        {
            var uri = new Uri(request.Url);

            // Only handle fs scheme.
            if (uri.Scheme != "fs")
            {
                return(false);
            }

            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 (_systemVolumes.Any(v => v.StartsWith(root)))
            {
                root = root + Path.VolumeSeparatorChar;
            }
            var filepath = root + uri.AbsolutePath;

            Task.Run(() =>
            {
                var mimeType = "";

                using (callback)
                {
                    if (File.Exists(filepath))
                    {
                        switch (Path.GetExtension(filepath).ToLower())
                        {
                        case ".css":
                            mimeType = "text/css";
                            break;

                        case ".html":
                        case ".htm":
                            mimeType = "text/html";
                            break;

                        case ".json":
                            mimeType = "application/json";
                            break;

                        case ".js":
                            mimeType = "text/javascript";
                            break;

                        case ".png":
                            mimeType = "image/png";
                            break;

                        case ".appcache":
                        case ".manifest":
                            mimeType = "text/cache-manifest";
                            break;

                        default:
                            mimeType = "application/octet-stream";
                            break;
                        }

                        var stream = new MemoryStream(File.ReadAllBytes(filepath));

                        //Reset the stream position to 0 so the stream can be copied into the underlying unmanaged buffer
                        stream.Position = 0;
                        //Populate the response values - No longer need to implement GetResponseHeaders (unless you need to perform a redirect)
                        ResponseLength = stream.Length;
                        MimeType       = mimeType;
                        StatusCode     = (int)HttpStatusCode.OK;
                        Stream         = stream;

                        callback.Continue();
                    }
                    else
                    {
                        ForErrorMessage("File not found.", HttpStatusCode.NotFound);
                        StatusCode = 404;
                        callback.Cancel();
                    }
                }
            });

            return(true);
        }
        /// <summary>
        /// The process request async.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public override CefReturnValue ProcessRequestAsync(IRequest request, ICallback callback)
        {
            var scheme = _requestSchemeHandlerProvider?.GetScheme(request.Url);

            if (scheme != null && scheme.UrlSchemeType == UrlSchemeType.LocalRquest)
            {
                _stream = null;
                var uri  = new Uri(request.Url);
                var path = uri.LocalPath;
                _mimeType = "application/json";

                bool isRequestAsync = _routeProvider.IsActionRouteAsync(path);
                if (isRequestAsync)
                {
                    ProcessRequestAsync(path);
                }
                else
                {
                    ProcessRequest(path);
                }
            }

            return(CefReturnValue.ContinueAsync);

            #region Process Request

            void ProcessRequest(string path)
            {
                Task.Run(() =>
                {
                    using (callback)
                    {
                        try
                        {
                            var response = new ChromelyResponse();
                            if (string.IsNullOrEmpty(path))
                            {
                                response.ReadyState = (int)ReadyState.ResponseIsReady;
                                response.Status     = (int)System.Net.HttpStatusCode.BadRequest;
                                response.StatusText = "Bad Request";

                                _chromelyResponse = response;
                            }
                            else
                            {
                                var parameters = request.Url.GetParameters();
                                var postData   = request.GetPostData();

                                _chromelyResponse = _requestTaskRunner.Run(path, parameters, postData);
                                string jsonData   = _serializerUtil.EnsureResponseDataIsJson(_chromelyResponse.Data);
                                var content       = Encoding.UTF8.GetBytes(jsonData);
                                _stream           = new MemoryStream();
                                _stream.Write(content, 0, content.Length);
                            }
                        }
                        catch (Exception exception)
                        {
                            _stream = null;
                            Logger.Instance.Log.LogError(exception, exception.Message);

                            _chromelyResponse =
                                new ChromelyResponse
                            {
                                Status = (int)HttpStatusCode.BadRequest,
                                Data   = "An error occured."
                            };
                        }

                        if (_stream == null)
                        {
                            callback.Cancel();
                        }
                        else
                        {
                            SetResponseInfoOnSuccess();
                            callback.Continue();
                        }
                    }
                });
            }

            #endregion

            #region Process Request Async

            void ProcessRequestAsync(string path)
            {
                Task.Run(async() =>
                {
                    using (callback)
                    {
                        try
                        {
                            var response = new ChromelyResponse();
                            if (string.IsNullOrEmpty(path))
                            {
                                response.ReadyState = (int)ReadyState.ResponseIsReady;
                                response.Status     = (int)System.Net.HttpStatusCode.BadRequest;
                                response.StatusText = "Bad Request";

                                _chromelyResponse = response;
                            }
                            else
                            {
                                var parameters = request.Url.GetParameters();
                                var postData   = request.GetPostData();

                                _chromelyResponse = await _requestTaskRunner.RunAsync(path, parameters, postData);
                                string jsonData   = _serializerUtil.EnsureResponseDataIsJson(_chromelyResponse.Data);
                                var content       = Encoding.UTF8.GetBytes(jsonData);
                                _stream           = new MemoryStream();
                                _stream.Write(content, 0, content.Length);
                            }
                        }
                        catch (Exception exception)
                        {
                            _stream = null;
                            Logger.Instance.Log.LogError(exception, exception.Message);

                            _chromelyResponse =
                                new ChromelyResponse
                            {
                                Status = (int)HttpStatusCode.BadRequest,
                                Data   = "An error occured."
                            };
                        }

                        if (_stream == null)
                        {
                            callback.Cancel();
                        }
                        else
                        {
                            SetResponseInfoOnSuccess();
                            callback.Continue();
                        }
                    }
                });
            }

            #endregion
        }