示例#1
0
        public void should_get_mimeType_with_fileName_by_suffix()
        {
            string file     = Environment.CurrentDirectory + @"\TestFiles\智慧市政综合指挥平台.docx";
            var    mimeType = MimeMapper.GetMimeMapping(file);

            Assert.AreEqual(mimeType, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        }
示例#2
0
 public Interpreter(IHtdocsSystem htdocsSystem, IFieldInjectFilter[] customFI, IPayloadIgnoreFilter[] customPF, MimeMapper mimeMapper)
 {
     this.htdocsSystem         = htdocsSystem;
     this.mimeMapper           = mimeMapper;
     this.customInjectFilters  = customFI;
     this.customPIgnoreFilters = customPF;
 }
        static void Main(string[] args)
        {
            var routes = new List <Route>()
            {
                new Route()
                {
                    Name     = "Products",
                    UrlRegex = @"\/.+\..+",
                    Method   = RequestMethod.GET,
                    Callable = request =>
                    {
                        string decodedUrl    = WebUtility.UrlDecode(request.Url);
                        string normalizedUrl = RepoPath + decodedUrl.Replace('/', '\\');
                        var    response      = new HttpResponse()
                        {
                            Content    = File.ReadAllBytes(normalizedUrl),
                            StatusCode = ResponseStatusCode.Ok
                        };
                        string fileType = decodedUrl.Substring(decodedUrl.LastIndexOf('.') + 1);
                        response.Header.ContentType = MimeMapper.MapMimeToType(fileType);
                        return(response);
                    }
                },
                new Route()
                {
                    Name     = "Products",
                    UrlRegex = @"^/",
                    Method   = RequestMethod.GET,
                    Callable = request =>
                    {
                        return(new HttpResponse()
                        {
                            ContentAsUtf8 = PageBuilder.BuildMyRepoPage(RepoPath + request.Url),
                            StatusCode = ResponseStatusCode.Ok
                        });
                    }
                },
                new Route()
                {
                    Name     = "Products",
                    UrlRegex = @"^/",
                    Method   = RequestMethod.POST,
                    Callable = request =>
                    {
                        PostRequestHandler.HandleFolderCreation(RepoPath + request.Url, request.Content);
                        //MemoryStream ms = new MemoryStream(bytes);
                        //Image image = Image.FromStream(ms,true,true);
                        //image.Save(@"D:\\UPLOADEDIMAGE.png", ImageFormat.Png);
                        return(new HttpResponse()
                        {
                            ContentAsUtf8 = PageBuilder.BuildMyRepoPage(RepoPath + request.Url),
                            StatusCode = ResponseStatusCode.Ok
                        });
                    }
                },
            };
            HttpServer server = new HttpServer(8081, routes);

            server.Listen();
        }
        public virtual IActionResult W(string u, int w = 200)
        {
            var thumbnailPath = MapWebRootPath(("/Thumbnail/" + u).Replace("//", "/"));
            var newPath       = Thumbnail.GetFileNameForHeight(thumbnailPath, w);

            if (System.IO.File.Exists(newPath) == false)
            {
                var path  = MapWebRootPath(u);
                var bytes = Thumbnail.MakeThumbnailImage(path, w, 0, "W");
                Directory.CreateDirectory(Path.GetDirectoryName(newPath));
                System.IO.File.WriteAllBytes(newPath, bytes);
            }
            FileInfo fileInfo = new FileInfo(newPath);

            Response.Headers["Cache-Control"] = "max-age=315360000";
            var etag = fileInfo.LastWriteTime.ToString("yyyyMMddHHmmss_") + fileInfo.Length.ToString();

            Response.Headers["Etag"]    = etag;
            Response.Headers["Date"]    = DateTime.Now.ToString("r");
            Response.Headers["Expires"] = DateTime.Now.AddYears(100).ToString("r");
            if (Request.Headers.ContainsKey("If-None-Match") && Request.Headers["If-None-Match"] == etag)
            {
                return(StatusCode(304));
            }
            var contentType = new MimeMapper().GetMimeFromExtension(Path.GetExtension(newPath));

            return(PhysicalFile(newPath, contentType));
        }
示例#5
0
        public SQLite(string sql, string connectionString, string returnType, string executionMode)
        {
            #region Initialize
            MimeType = MimeMapper.GetMimeType(returnType);
            if (string.IsNullOrEmpty(MimeType))
            {
                returnType = "json";
                MimeType   = MimeMapper.GetMimeType(returnType);
            }

            this.sql = sql;
            this.connectionString = connectionString;
            this.returnType       = returnType;
            this.executionMode    = executionMode;
            //Data = Encoding.UTF8.GetBytes(Parse(sql, connectionString, returnType, executionMode));

            StatusCode = 200;
            StatusText = "OK";
            Headers    = new NameValueCollection();
            //Stream = new MemoryStream(Data);



            //Data Source=database\master.db;Pooling=true;FailIfMissing=true;
            #endregion
        }
示例#6
0
        private bool ProcessAssmblyEmbeddedFile(string url, string file, string fileAbsolutePath)
        {
            var scheme = _requestSchemeHandlerProvider?.GetScheme(url);

            if (scheme == null ||
                scheme.AssemblyOptions == null ||
                scheme.AssemblyOptions.TargetAssembly == null ||
                scheme.UrlSchemeType != UrlSchemeType.AssemblyResource)
            {
                return(false);
            }

            var option       = scheme.AssemblyOptions;
            var manifestName = string.Join(".", option.DefaultNamespace, option.RootFolder, _regex.Replace(fileAbsolutePath, ".")).Replace("..", ".").Replace("..", ".");
            var stream       = option.TargetAssembly.GetManifestResourceStream(manifestName);

            if (stream != null && stream.Length > 0)
            {
                stream.CopyTo(_chromelyResource.Content);
                string extension = Path.GetExtension(file);
                _chromelyResource.MimeType = MimeMapper.GetMimeType(extension);
                return(true);
            }

            return(false);
        }
示例#7
0
        /// <summary>
        /// 添加本地文件
        /// </summary>
        /// <param name="filePath">本地文件路径</param>
        /// <param name="remoteFile">服务Id</param>
        /// <returns></returns>
        public MetaInfo Add(string filePath, string remoteFile)
        {
            try
            {
                _logger.DebugFormat("Add File filePath:{0}, remoteId:{1}", filePath, remoteFile);

                MongoGridFSCreateOptions option = new MongoGridFSCreateOptions
                {
                    Id          = remoteFile,
                    UploadDate  = DateTime.Now,
                    ContentType = MimeMapper.GetMimeMapping(filePath),
                };

                using (var stream = new FileStream(filePath, FileMode.Open))
                {
                    MongoGridFS fs = new MongoGridFS(_context.DataBase);

                    var info = fs.Upload(stream, remoteFile, option);
                    return(new MetaInfo
                    {
                        fileName = remoteFile,
                        MD5 = info.MD5,
                        MimeType = info.ContentType,
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                _logger.Error(ex.StackTrace);
                throw;
            }
        }
        private bool ProcessLocalFile(string file, CefCallback callback)
        {
            // Check if file exists and not empty
            var fileInfo = new FileInfo(file);

            if ((fileInfo.Exists) && fileInfo.Length > 0)
            {
                Task.Run(() =>
                {
                    using (callback)
                    {
                        try
                        {
                            _fileBytes = File.ReadAllBytes(file);

                            string extension = Path.GetExtension(file);
                            _mime            = MimeMapper.GetMimeType(extension);
                        }
                        catch (Exception exception)
                        {
                            Logger.Instance.Log.LogError(exception, exception.Message);
                        }
                        finally
                        {
                            callback.Continue();
                        }
                    }
                });

                return(true);
            }

            return(false);
        }
示例#9
0
        protected override bool ProcessRequest(CefRequest request, CefCallback callback)
        {
            var u    = new Uri(request.Url);
            var file = u.Authority + u.AbsolutePath;

            _totalBytesRead = 0;
            _fileBytes      = null;
            _completed      = false;

            var fileInfo = new FileInfo(file);

            // Check if file exists
            if (!fileInfo.Exists)
            {
                _chromelyErrorHandler.HandleResourceError(ResourceStatus.FileNotFound, file, out _statusCode, out _statusText);
                _fileBytes = _statusText.GetMemoryStream();

                callback.Continue();
            }
            // Check if file exists but empty
            else if (fileInfo.Length == 0)
            {
                _chromelyErrorHandler.HandleResourceError(ResourceStatus.ZeroFileSize, file, out _statusCode, out _statusText);
                _fileBytes = _statusText.GetMemoryStream();
                callback.Continue();
            }
            else
            {
                Task.Run(() =>
                {
                    using (callback)
                    {
                        try
                        {
                            _fileBytes = File.ReadAllBytes(file);

                            string extension = Path.GetExtension(file);
                            _mime            = MimeMapper.GetMimeType(extension);
                            _statusCode      = ResourceConstants.StatusOK;
                            _statusText      = ResourceConstants.StatusOKText;
                        }
                        catch (Exception exception)
                        {
                            _chromelyErrorHandler.HandleResourceError(ResourceStatus.FileProcessingError, file, exception, out _statusCode, out _statusText);
                            _fileBytes = _statusText.GetMemoryStream();
                        }
                        finally
                        {
                            callback.Continue();
                        }
                    }
                });

                return(true);
            }

            callback.Dispose();
            return(false);
        }
        /// <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);
        }
示例#11
0
        public EngineInitializationFactory(ServerConfig serverConfig, FilterConfig filterConfig)
        {
            this.serverConfig = serverConfig;
            this.filterConfig = filterConfig;

            pathResolver      = new PathResolver(serverConfig.RootDirectory);
            mimeMapper        = MimeMapper.FromApacheFile(InternalEngineConfiguration.DirectoryTree.ApacheMimeTypesFileRelativePath, pathResolver);
            httpStreamMarshal = BuildHttpStreamMarshal();
        }
示例#12
0
        public PdfHandler(PdfDocument pdf, int pages)
        {
            #region Initialize
            this.pdf   = pdf;
            this.pages = pages;

            MimeType   = MimeMapper.GetMimeType("pdf");
            StatusCode = 200;
            StatusText = "OK";
            Headers    = new NameValueCollection();
            #endregion
        }
        protected ResumeActionResultBase(string fileName)
        {
            MimeMapper mimeMapper  = new MimeMapper();
            string     contentType = mimeMapper.GetMimeFromPath(fileName);

            if (string.IsNullOrEmpty(contentType))
            {
                contentType = MimeMapper.DefaultMime;
            }
            _fileName   = fileName;
            ContentType = contentType;
        }
示例#14
0
	/// <summary>
	/// Creates the mime mapper.
	/// </summary>
	/// <param name="typesCount">Number of elements which make up the association table.</param>
	/// <returns>Mime types mapper.</returns>
	static MimeMapper CreateMapper(int typesCount)
	{
		var mapper = new MimeMapper();
		// read available maps.
		for ( int i = 0; i < typesCount; i++ ) {
			string[] inputs = Console.ReadLine().Split( ' ' );
			string ext	= inputs[ 0 ]; // file extension
			string mime	= inputs[ 1 ]; // MIME type.
			// register a map type.
			mapper.Register( ext, mime );
		}
		return	mapper;
	}
        private bool ProcessAssmblyEmbeddedFile(string url, string file, string fileAbsolutePath, CefCallback callback)
        {
            var urlScheme = _config?.UrlSchemes?.GetScheme(url, UrlSchemeType.AssemblyResource);
            var option    = urlScheme.AssemblyOptions;

            if (option == null || option.TargetAssembly == null)
            {
                return(false);
            }

            var manifestName = string.Join(".", option.DefaultNamespace, option.RootFolder, _regex.Replace(fileAbsolutePath, ".")).Replace("..", ".").Replace("..", ".");
            var stream       = option.TargetAssembly.GetManifestResourceStream(manifestName);

            if (stream != null && stream.Length > 0)
            {
                Task.Run(() =>
                {
                    using (callback)
                    {
                        try
                        {
                            _fileBytes = new byte[stream.Length];
                            stream.Read(_fileBytes, 0, (int)stream.Length);
                            stream.Flush();
                            stream.Dispose();
                            string extension = Path.GetExtension(file);
                            _mime            = MimeMapper.GetMimeType(extension);
                        }
                        catch (Exception exception)
                        {
                            Logger.Instance.Log.LogError(exception, exception.Message);
                        }
                        finally
                        {
                            callback.Continue();
                        }
                    }
                });

                return(true);
            }
            else
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }

            return(false);
        }
示例#16
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 bool ProcessRequestAsync(IRequest request, ICallback callback)
        {
            var u    = new Uri(request.Url);
            var file = u.Authority + u.AbsolutePath;

            // Check if file exists and not empty
            var fileInfo = new FileInfo(file);

            if ((fileInfo.Exists) && fileInfo.Length > 0)
            {
                Task.Run(() =>
                {
                    using (callback)
                    {
                        try
                        {
                            _chromelyResponse = new ChromelyResponse {
                                Status = (int)HttpStatusCode.OK, Data = "OK."
                            };

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

                            string extension = Path.GetExtension(file);
                            _mimeType        = MimeMapper.GetMimeType(extension);
                        }
                        catch (Exception exception)
                        {
                            Log.Error(exception);

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

                return(true);
            }

            Log.Error($"File {request.Url} is not valid.");
            callback.Dispose();
            return(false);
        }
示例#17
0
        private bool ProcessLocalFile(string file, CefCallback callback)
        {
            var fileInfo = new FileInfo(file);

            // Check if file exists
            if (!fileInfo.Exists)
            {
                _chromelyErrorHandler.HandleResourceError(ResourceStatus.FileNotFound, file, out _statusCode, out _statusText);
                _fileBytes = _statusText.GetMemoryStream();
                callback.Continue();
            }
            // Check if file exists but empty
            else if (fileInfo.Length == 0)
            {
                _chromelyErrorHandler.HandleResourceError(ResourceStatus.ZeroFileSize, file, out _statusCode, out _statusText);
                _fileBytes = _statusText.GetMemoryStream();
                callback.Continue();
            }
            else
            {
                Task.Run(() =>
                {
                    using (callback)
                    {
                        try
                        {
                            _fileBytes = File.ReadAllBytes(file);

                            string extension = Path.GetExtension(file);
                            _mime            = MimeMapper.GetMimeType(extension);
                            _statusCode      = ResourceConstants.StatusOK;
                            _statusText      = ResourceConstants.StatusOKText;
                        }
                        catch (Exception exception)
                        {
                            _chromelyErrorHandler.HandleResourceError(ResourceStatus.FileProcessingError, file, exception, out _statusCode, out _statusText);
                            _fileBytes = _statusText.GetMemoryStream();
                        }
                        finally
                        {
                            callback.Continue();
                        }
                    }
                });

                return(true);
            }

            return(false);
        }
示例#18
0
        private bool ProcessLocalFile(string file, CefCallback callback)
        {
            _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)
                    {
                        try
                        {
                            var fileBytes             = File.ReadAllBytes(file);
                            _chromelyResource.Content = new MemoryStream(fileBytes);

                            string extension             = Path.GetExtension(file);
                            _chromelyResource.MimeType   = MimeMapper.GetMimeType(extension);
                            _chromelyResource.StatusCode = ResourceConstants.StatusOK;
                            _chromelyResource.StatusText = ResourceConstants.StatusOKText;
                        }
                        catch (Exception exception)
                        {
                            _chromelyResource = _chromelyErrorHandler.HandleError(_fileInfo, exception);
                        }
                        finally
                        {
                            callback.Continue();
                        }
                    }
                });

                return(true);
            }

            return(false);
        }
示例#19
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 bool ProcessRequestAsync(IRequest request, ICallback callback)
        {
            var u    = new Uri(request.Url);
            var file = u.Authority + u.AbsolutePath;

            if (File.Exists(file))
            {
                Task.Factory.StartNew(() =>
                {
                    using (callback)
                    {
                        try
                        {
                            this.mChromelyResponse = new ChromelyResponse {
                                Status = (int)HttpStatusCode.OK, Data = "OK."
                            };

                            byte[] fileBytes = File.ReadAllBytes(file);
                            this.mStream     = new MemoryStream(fileBytes);

                            string extension = Path.GetExtension(file);
                            this.mMimeType   = MimeMapper.GetMimeType(extension);
                        }
                        catch (Exception exception)
                        {
                            Log.Error(exception);

                            this.mChromelyResponse =
                                new ChromelyResponse
                            {
                                Status = (int)HttpStatusCode.BadRequest,
                                Data   = "An error occured."
                            };
                        }
                        finally
                        {
                            callback.Continue();
                        }
                    }
                });

                return(true);
            }

            Log.Error($"File {request.Url} is not valid.");
            callback.Dispose();
            return(false);
        }
示例#20
0
        private bool ProcessLocalFile(string file)
        {
            // Check if file exists and not empty
            var fileInfo = new FileInfo(file);

            if ((fileInfo.Exists) && fileInfo.Length > 0)
            {
                byte[] fileBytes = File.ReadAllBytes(file);
                _chromelyResource.Content = new MemoryStream(fileBytes);

                string extension = Path.GetExtension(file);
                _chromelyResource.MimeType = MimeMapper.GetMimeType(extension);
            }

            return(false);
        }
示例#21
0
        public ZipHandler(string zipString)
        {
            #region Initialize
            this.zipString = zipString;

            MimeType   = MimeMapper.GetMimeType("xlsx");
            StatusCode = 200;
            StatusText = "OK";
            Headers    = new NameValueCollection();
            #endregion

            var path = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
            if (File.Exists(Path.Combine(path, "Configurations.xml")))
            {
                configuration = Configuration.Load(Path.Combine(path, "Configurations.xml"));
            }
        }
示例#22
0
        /// <summary>
        ///     processing of execution - main method of action
        /// </summary>
        /// <returns> </returns>
        protected override object MainProcess()
        {
            var result = new FileDescriptor
            {
                Name = _assembly.GetName().Name + "/" + _resourcename, LastWriteTime = Application.StartTime, Role = ""
            };

            using (var stream = _assembly.GetManifestResourceStream(_resourcename)) {
                Debug.Assert(stream != null, "stream != null");
                var sr = new StreamReader(stream);
                result.Content = sr.ReadToEnd();
            }

            result.Length   = result.Content.Length;
            result.MimeType = MimeMapper.Get(_resourcename);
            return(result);
        }
        public DatabaseHandler(string profileName, string query)
        {
            #region Initialize
            this.profileName = profileName;
            this.query       = query;

            MimeType   = MimeMapper.GetMimeType("zip");
            StatusCode = 200;
            StatusText = "OK";
            Headers    = new NameValueCollection();
            #endregion

            var path = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
            if (File.Exists(Path.Combine(path, "Configurations.xml")))
            {
                configuration = Configuration.Load(Path.Combine(path, "Configurations.xml"));
            }
        }
        protected override bool ProcessRequest(CefRequest request, CefCallback callback)
        {
            var u    = new Uri(request.Url);
            var file = u.Authority + u.AbsolutePath;

            _totalBytesRead = 0;
            _fileBytes      = null;
            _completed      = false;

            // Check if file exists and not empty
            var fileInfo = new FileInfo(file);

            if ((fileInfo.Exists) && fileInfo.Length > 0)
            {
                Task.Run(() =>
                {
                    using (callback)
                    {
                        try
                        {
                            _fileBytes = File.ReadAllBytes(file);

                            string extension = Path.GetExtension(file);
                            _mime            = MimeMapper.GetMimeType(extension);
                        }
                        catch (Exception exception)
                        {
                            Logger.Instance.Log.Error(exception);
                        }
                        finally
                        {
                            callback.Continue();
                        }
                    }
                });

                return(true);
            }

            callback.Dispose();
            return(false);
        }
        public IActionResult DownloadFile(string path, long timestamp, string sign)
        {
            if (IsSignParameter())
            {
                SortedDictionary <string, string> keys = new SortedDictionary <string, string>();
                keys[nameof(path)]      = path.ToString();
                keys[nameof(timestamp)] = timestamp.ToString();
                if (GetSignHash(keys).Equals(sign, System.StringComparison.CurrentCultureIgnoreCase) == false)
                {
                    return(StatusCode(404));
                }
            }
            if (System.IO.File.Exists(path) == false)
            {
                return(StatusCode(404));
            }
            var mime = new MimeMapper().GetMimeFromPath(path);

            return(PhysicalFile(path, mime, true));
        }
示例#26
0
        /// <summary>
        /// The process request.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        protected override bool ProcessRequest(CefRequest request, CefCallback callback)
        {
            var u    = new Uri(request.Url);
            var file = u.Authority + u.AbsolutePath;

            this.mTotalBytesRead = 0;
            this.mFileBytes      = null;
            this.mCompleted      = false;

            if (File.Exists(file))
            {
                Task.Factory.StartNew(() =>
                {
                    using (callback)
                    {
                        try
                        {
                            this.mFileBytes = File.ReadAllBytes(file);

                            string extension = Path.GetExtension(file);
                            this.mMime       = MimeMapper.GetMimeType(extension);
                        }
                        catch (Exception exception)
                        {
                            Log.Error(exception);
                        }
                        finally
                        {
                            callback.Continue();
                        }
                    }
                });

                return(true);
            }

            callback.Dispose();
            return(false);
        }
        protected override bool ProcessRequest(CefRequest request, CefCallback callback)
        {
            var u    = new Uri(request.Url);
            var file = u.Authority + u.AbsolutePath;

            _totalBytesRead = 0;
            _fileBytes      = null;
            _completed      = false;

            var fileInfo = new FileInfo(file);

            // Check if file exists
            if (!fileInfo.Exists)
            {
                var status = ResourceFileStatus.FileNotFound.GetStatus();
                _status     = status.Item1;
                _statusText = status.Item2;
                _fileBytes  = _statusText.GetMemoryStream();

                Logger.Instance.Log.LogWarning($"File: {file}: {_statusText}");

                callback.Continue();
            }
            // Check if file exists but empty
            else if (fileInfo.Length == 0)
            {
                var status = ResourceFileStatus.ZeroFileSize.GetStatus();
                _status     = status.Item1;
                _statusText = status.Item2;
                _fileBytes  = _statusText.GetMemoryStream();

                Logger.Instance.Log.LogWarning($"File: {file}: {_statusText}");

                callback.Continue();
            }
            else
            {
                Task.Run(() =>
                {
                    using (callback)
                    {
                        try
                        {
                            _fileBytes = File.ReadAllBytes(file);

                            string extension = Path.GetExtension(file);
                            _mime            = MimeMapper.GetMimeType(extension);
                            var status       = ResourceFileStatus.FileFound.GetStatus();
                            _status          = status.Item1;
                            _statusText      = status.Item2;
                        }
                        catch (Exception exception)
                        {
                            var status  = ResourceFileStatus.FileProcessingError.GetStatus();
                            _status     = status.Item1;
                            _statusText = status.Item2;
                            _fileBytes  = _statusText.GetMemoryStream();

                            Logger.Instance.Log.LogError(exception, exception.Message);
                        }
                        finally
                        {
                            callback.Continue();
                        }
                    }
                });

                return(true);
            }

            callback.Dispose();
            return(false);
        }
    /// <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(CefRequest request, CefCallback callback)
    {
        var uri = new Uri(request.Url);
        var scheme = _config.UrlSchemes.GetScheme(request.Url);
        var isFolderResourceScheme = scheme is not null && scheme.IsUrlSchemeFolderResource();

        var u = new Uri(request.Url);
        var file = isFolderResourceScheme
                    ? scheme.GetResourceFolderFile(u.AbsolutePath)
                    : 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);
                        _chromelyResource.StatusCode = ResourceConstants.StatusOK;
                        _chromelyResource.StatusText = ResourceConstants.StatusOKText;
                    }
                    catch (Exception exception)
                    {
                        _chromelyResource = _chromelyErrorHandler.HandleError(_fileInfo, exception);
                    }

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

        return CefReturnValue.ContinueAsync;
    }
示例#29
0
        /// <summary>
        /// The process request.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        protected override bool ProcessRequest(CefRequest request, CefCallback callback)
        {
            //var baseRelative = _baseDir.Replace("\\", "/");
            var u = new Uri(request.Url);

            var file = Path.Join(AppDomain.CurrentDomain.BaseDirectory, _appDirectory, u.AbsolutePath);

            //if (first == null)
            //{
            //    first = Path.GetDirectoryName(file);
            //}
            //else
            //{
            //    file = Path.Join(first, u.AbsolutePath);
            //}


            this.mTotalBytesRead = 0;
            this.mFileBytes      = null;
            this.mCompleted      = false;

            if (File.Exists(file))
            {
                Task.Factory.StartNew(() =>
                {
                    using (callback)
                    {
                        try
                        {
                            this.mFileBytes = File.ReadAllBytes(file);

                            string extension = Path.GetExtension(file);
                            Log.Info(extension);
                            if (extension == ".wasm")
                            {
                                this.mMime = "application/wasm";
                            }
                            else if (extension == ".dll")
                            {
                                this.mMime = "application/octet-stream";
                            }
                            else if (extension == ".json")
                            {
                                this.mMime = "application/json";
                            }
                            else if (extension == ".woff" || extension == ".woff2")
                            {
                                this.mMime = "application/font-woff";
                            }
                            else
                            {
                                this.mMime = MimeMapper.GetMimeType(extension);
                            }
                        }
                        catch (Exception exception)
                        {
                            Log.Error(exception);
                        }
                        finally
                        {
                            callback.Continue();
                        }
                    }
                });

                return(true);
            }

            callback.Dispose();
            return(false);
        }
示例#30
0
        private bool ProcessAssmblyEmbeddedFile(string url, string file, string fileAbsolutePath, CefCallback callback)
        {
            var urlScheme = _config?.UrlSchemes?.GetScheme(url, UrlSchemeType.AssemblyResource);
            var option    = urlScheme.AssemblyOptions;

            if (option == null || option.TargetAssembly == null)
            {
                return(false);
            }

            var manifestName = string.Join(".", option.DefaultNamespace, option.RootFolder, _regex.Replace(fileAbsolutePath, ".")).Replace("..", ".").Replace("..", ".");
            var stream       = option.TargetAssembly.GetManifestResourceStream(manifestName);

            // Check if file exists
            if (stream == null)
            {
                _chromelyResource = _chromelyErrorHandler.HandleError(stream);
                callback.Continue();
            }
            // Check if file exists but empty
            else if (stream.Length == 0)
            {
                _chromelyResource = _chromelyErrorHandler.HandleError(stream);
                stream.Dispose();

                callback.Continue();
            }
            else
            {
                Task.Run(() =>
                {
                    using (callback)
                    {
                        try
                        {
                            var fileBytes = new byte[stream.Length];
                            stream.Read(fileBytes, 0, (int)stream.Length);
                            stream.Flush();
                            stream.Dispose();

                            _chromelyResource.Content    = new MemoryStream(fileBytes);
                            string extension             = Path.GetExtension(file);
                            _chromelyResource.MimeType   = MimeMapper.GetMimeType(extension);
                            _chromelyResource.StatusCode = ResourceConstants.StatusOK;
                            _chromelyResource.StatusText = ResourceConstants.StatusOKText;
                        }
                        catch (Exception exception)
                        {
                            _chromelyResource = _chromelyErrorHandler.HandleError(_fileInfo, exception);
                        }
                        finally
                        {
                            callback.Continue();
                        }
                    }
                });

                return(true);
            }

            return(false);
        }
        /// <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;
        }