Ejemplo n.º 1
0
        public HTTPResponse GetFile(HTTPRequest request)
        {
            if (this.filePath == null)
            {
                return(null);
            }

            var path = request.path.StartsWith("/") ? request.path.Substring(1): request.path;

            path = filePath + path;
            this.logger(LogLevel.Debug, $"Returning static file...{path}");

            CacheEntry entry;

            lock (_files)
            {
                if (_files.ContainsKey(request.path))
                {
                    entry = _files[request.path];
                }
                else
                {
                    entry = null;
                }
            }

            if (entry != null)
            {
                if (entry.path != null)
                {
                    var lastMod = File.GetLastWriteTime(path);

                    if (lastMod != entry.lastModified)
                    {
                        entry.Reload();
                        entry.lastModified = lastMod;
                    }
                }
            }
            else
            {
                if (!File.Exists(path))
                {
                    logger(LogLevel.Warning, "Nothing found...");
                    return(null);
                }

                entry = new CacheEntry();
                entry.lastModified = File.GetLastWriteTime(path);
                entry.path         = path;

                entry.Reload();

                lock (_files)
                {
                    _files[request.path] = entry;
                }
            }

            if (request.headers.ContainsKey("If-None-Match"))
            {
                var hash = request.headers["If-None-Match"];
                if (hash.Equals(entry.hash))
                {
                    return(HTTPResponse.NotModified(entry.hash, defaultMaxAge));
                }
            }

            var result = HTTPResponse.FromBytes(entry.bytes);

            if (entry.isCompressed)
            {
                result.headers["Content-Encoding"] = "gzip";
            }

            result.headers["Content-Type"] = entry.contentType;

            result.headers["Content-Description"] = "File Transfer";

            var fileName = Path.GetFileName(request.path);

            if (entry.isDownload)
            {
                result.headers["Content-Disposition"] = "attachment; filename=\"" + fileName + "\"";
            }

            result.headers["Content-Transfer-Encoding"] = "binary";
            result.headers["Connection"] = "Keep-Alive";
            //result.headers["Expires"] = "0";
            result.headers["Cache-Control"] = "max-age=" + defaultMaxAge + ", public";
            result.headers["Pragma"]        = "public";


            result.headers["Last-Modified"] = entry.lastModified.ToString("r");

            result.headers["ETag"] = entry.hash;

            return(result);
        }