From 07a8e49c4b1e4a2dddbaa49ab6f1ff4f271fbf20 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 6 Jan 2019 20:35:36 +0100 Subject: [PATCH 1/2] Cleanup some small things --- .../ApplicationHost.cs | 5 +- .../HttpClientManager/HttpClientManager.cs | 2 +- .../HttpServer/HttpListenerHost.cs | 136 +++++++----------- .../HttpServer/HttpResultFactory.cs | 39 ++--- .../HttpServer/RangeRequestWriter.cs | 5 - .../HttpServer/ResponseFilter.cs | 28 +--- .../Services/HttpResult.cs | 10 +- .../Services/RequestHelper.cs | 2 +- 8 files changed, 77 insertions(+), 150 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 9b9c6146fa..8d161d3751 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -238,7 +238,6 @@ namespace Emby.Server.Implementations { get { - #if BETA return PackageVersionClass.Beta; #endif @@ -552,7 +551,7 @@ namespace Emby.Server.Implementations protected void RegisterSingleInstance(T obj, bool manageLifetime = true) where T : class { - Container.RegisterSingleton(obj); + Container.RegisterInstance(obj); if (manageLifetime) { @@ -617,7 +616,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError(ex, "Error loading assembly {file}", file); + Logger.LogError(ex, "Error loading assembly {File}", file); return null; } } diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs index d3ba1b683e..c95093fc58 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs @@ -389,7 +389,7 @@ namespace Emby.Server.Implementations.HttpClientManager { options.ResourcePool?.Release(); - throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true }; + throw new HttpException($"Connection to {options.Url} timed out") { IsTimedOut = true }; } if (options.LogRequest) diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs index 69ca0f85b6..91b2e9ded6 100644 --- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -1,27 +1,28 @@ -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Net; -using Microsoft.Extensions.Logging; + using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; +using Emby.Server.Implementations.Net; using Emby.Server.Implementations.Services; +using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Common.Security; using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Net; +using MediaBrowser.Model.Events; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Services; using MediaBrowser.Model.Text; -using System.Net.Sockets; -using Emby.Server.Implementations.Net; -using MediaBrowser.Model.Events; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.HttpServer { @@ -55,40 +56,33 @@ namespace Emby.Server.Implementations.HttpServer private IWebSocketListener[] _webSocketListeners = Array.Empty(); private readonly List _webSocketConnections = new List(); - public HttpListenerHost(IServerApplicationHost applicationHost, + public HttpListenerHost( + IServerApplicationHost applicationHost, ILogger logger, IServerConfigurationManager config, - string defaultRedirectPath, INetworkManager networkManager, ITextEncoding textEncoding, IJsonSerializer jsonSerializer, IXmlSerializer xmlSerializer, Func> funcParseFn) + string defaultRedirectPath, + INetworkManager networkManager, + ITextEncoding textEncoding, + IJsonSerializer jsonSerializer, + IXmlSerializer xmlSerializer, + Func> funcParseFn) { - Instance = this; - _appHost = applicationHost; + _logger = logger; + _config = config; DefaultRedirectPath = defaultRedirectPath; _networkManager = networkManager; _textEncoding = textEncoding; _jsonSerializer = jsonSerializer; _xmlSerializer = xmlSerializer; - _config = config; - - _logger = logger; _funcParseFn = funcParseFn; - ResponseFilters = new Action[] { }; + Instance = this; + ResponseFilters = Array.Empty>(); } public string GlobalResponse { get; set; } - readonly Dictionary _mapExceptionToStatusCode = new Dictionary - { - {typeof (ResourceNotFoundException), 404}, - {typeof (RemoteServiceUnavailableException), 502}, - {typeof (FileNotFoundException), 404}, - //{typeof (DirectoryNotFoundException), 404}, - {typeof (SecurityException), 401}, - {typeof (PaymentRequiredException), 402}, - {typeof (ArgumentException), 400} - }; - protected ILogger Logger { get @@ -111,9 +105,9 @@ namespace Emby.Server.Implementations.HttpServer { //Exec all RequestFilter attributes with Priority < 0 var attributes = GetRequestFilterAttributes(requestDto.GetType()); - var i = 0; - var count = attributes.Count; + int count = attributes.Count; + int i = 0; for (; i < count && attributes[i].Priority < 0; i++) { var attribute = attributes[i]; @@ -176,10 +170,7 @@ namespace Emby.Server.Implementations.HttpServer _webSocketConnections.Add(connection); } - if (WebSocketConnected != null) - { - WebSocketConnected?.Invoke(this, new GenericEventArgs(connection)); - } + WebSocketConnected?.Invoke(this, new GenericEventArgs(connection)); } private void Connection_Closed(object sender, EventArgs e) @@ -192,8 +183,7 @@ namespace Emby.Server.Implementations.HttpServer private Exception GetActualException(Exception ex) { - var agg = ex as AggregateException; - if (agg != null) + if (ex is AggregateException agg) { var inner = agg.InnerException; if (inner != null) @@ -215,27 +205,17 @@ namespace Emby.Server.Implementations.HttpServer private int GetStatusCode(Exception ex) { - if (ex is ArgumentException) + switch (ex) { - return 400; + case ArgumentException _: return 400; + case SecurityException _: return 401; + case PaymentRequiredException _: return 402; + case DirectoryNotFoundException _: + case FileNotFoundException _: + case ResourceNotFoundException _: return 404; + case RemoteServiceUnavailableException _: return 502; + default: return 500; } - - var exceptionType = ex.GetType(); - - int statusCode; - if (!_mapExceptionToStatusCode.TryGetValue(exceptionType, out statusCode)) - { - if (ex is DirectoryNotFoundException) - { - statusCode = 404; - } - else - { - statusCode = 500; - } - } - - return statusCode; } private async Task ErrorHandler(Exception ex, IRequest httpReq, bool logExceptionStackTrace, bool logExceptionMessage) @@ -321,29 +301,22 @@ namespace Emby.Server.Implementations.HttpServer } } - private readonly Dictionary _skipLogExtensions = new Dictionary(StringComparer.OrdinalIgnoreCase) + private static readonly string[] _skipLogExtensions = { - {".js", 0}, - {".css", 0}, - {".woff", 0}, - {".woff2", 0}, - {".ttf", 0}, - {".html", 0} + ".js", + ".css", + ".woff", + ".woff2", + ".ttf", + ".html" }; private bool EnableLogging(string url, string localPath) { var extension = GetExtension(url); - if (string.IsNullOrEmpty(extension) || !_skipLogExtensions.ContainsKey(extension)) - { - if (string.IsNullOrEmpty(localPath) || localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1) - { - return true; - } - } - - return false; + return ((string.IsNullOrEmpty(extension) || !_skipLogExtensions.Contains(extension)) + && (string.IsNullOrEmpty(localPath) || localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)); } private string GetExtension(string url) @@ -566,9 +539,7 @@ namespace Emby.Server.Implementations.HttpServer return; } - if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) || - string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) || - localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1) + if (localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1) { httpRes.StatusCode = 200; httpRes.ContentType = "text/html"; @@ -723,7 +694,7 @@ namespace Emby.Server.Implementations.HttpServer }; } - _logger.LogError("Could not find handler for {pathInfo}", pathInfo); + _logger.LogError("Could not find handler for {PathInfo}", pathInfo); return null; } @@ -737,14 +708,13 @@ namespace Emby.Server.Implementations.HttpServer private void RedirectToSecureUrl(IHttpRequest httpReq, IResponse httpRes, string url) { - int currentPort; - Uri uri; - if (Uri.TryCreate(url, UriKind.Absolute, out uri)) + if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri)) { - currentPort = uri.Port; - var builder = new UriBuilder(uri); - builder.Port = _config.Configuration.PublicHttpsPort; - builder.Scheme = "https"; + var builder = new UriBuilder(uri) + { + Port = _config.Configuration.PublicHttpsPort, + Scheme = "https" + }; url = builder.Uri.ToString(); RedirectToUrl(httpRes, url); @@ -844,12 +814,6 @@ namespace Emby.Server.Implementations.HttpServer public Task DeserializeJson(Type type, Stream stream) { - //using (var reader = new StreamReader(stream)) - //{ - // var json = reader.ReadToEnd(); - // logger.LogInformation(json); - // return _jsonSerializer.DeserializeFromString(json, type); - //} return _jsonSerializer.DeserializeFromStreamAsync(stream, type); } diff --git a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs index 73b2afe640..3d0fb577a2 100644 --- a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs +++ b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs @@ -412,8 +412,10 @@ namespace Emby.Server.Implementations.HttpServer serializer.WriteObject(xw, from); xw.Flush(); ms.Seek(0, SeekOrigin.Begin); - var reader = new StreamReader(ms); - return reader.ReadToEnd(); + using (var reader = new StreamReader(ms)) + { + return reader.ReadToEnd(); + } } } } @@ -425,7 +427,7 @@ namespace Emby.Server.Implementations.HttpServer { responseHeaders["ETag"] = string.Format("\"{0}\"", cacheKeyString); - var noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1; + bool noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1; if (!noCache) { @@ -463,8 +465,7 @@ namespace Emby.Server.Implementations.HttpServer }); } - public Task GetStaticFileResult(IRequest requestContext, - StaticFileResultOptions options) + public Task GetStaticFileResult(IRequest requestContext, StaticFileResultOptions options) { var path = options.Path; var fileShare = options.FileShare; @@ -699,36 +700,26 @@ namespace Emby.Server.Implementations.HttpServer var ifModifiedSinceHeader = requestContext.Headers.Get("If-Modified-Since"); - if (!string.IsNullOrEmpty(ifModifiedSinceHeader)) + if (!string.IsNullOrEmpty(ifModifiedSinceHeader) + && DateTime.TryParse(ifModifiedSinceHeader, out DateTime ifModifiedSince) + && IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified)) { - DateTime ifModifiedSince; - - if (DateTime.TryParse(ifModifiedSinceHeader, out ifModifiedSince)) - { - if (IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified)) - { - return true; - } - } + return true; } var ifNoneMatchHeader = requestContext.Headers.Get("If-None-Match"); - var hasCacheKey = !cacheKey.Equals(Guid.Empty); + bool hasCacheKey = !cacheKey.Equals(Guid.Empty); // Validate If-None-Match - if ((hasCacheKey || !string.IsNullOrEmpty(ifNoneMatchHeader))) + if ((hasCacheKey && !string.IsNullOrEmpty(ifNoneMatchHeader))) { - Guid ifNoneMatch; - ifNoneMatchHeader = (ifNoneMatchHeader ?? string.Empty).Trim('\"'); - if (Guid.TryParse(ifNoneMatchHeader, out ifNoneMatch)) + if (Guid.TryParse(ifNoneMatchHeader, out Guid ifNoneMatch) + && cacheKey.Equals(ifNoneMatch)) { - if (hasCacheKey && cacheKey.Equals(ifNoneMatch)) - { - return true; - } + return true; } } diff --git a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs index dc20ee1a24..795f96f2c2 100644 --- a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs +++ b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs @@ -40,8 +40,6 @@ namespace Emby.Server.Implementations.HttpServer /// private static readonly CultureInfo UsCulture = new CultureInfo("en-US"); - public List Cookies { get; private set; } - /// /// Additional HTTP Headers /// @@ -75,7 +73,6 @@ namespace Emby.Server.Implementations.HttpServer Headers["Accept-Ranges"] = "bytes"; StatusCode = HttpStatusCode.PartialContent; - Cookies = new List(); SetRangeValues(contentLength); } @@ -223,7 +220,5 @@ namespace Emby.Server.Implementations.HttpServer get { return (HttpStatusCode)Status; } set { Status = (int)value; } } - - public string StatusDescription { get; set; } } } diff --git a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs index f38aa5ea06..afaee59f39 100644 --- a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs +++ b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs @@ -25,14 +25,11 @@ namespace Emby.Server.Implementations.HttpServer public void FilterResponse(IRequest req, IResponse res, object dto) { // Try to prevent compatibility view - //res.AddHeader("X-UA-Compatible", "IE=Edge"); res.AddHeader("Access-Control-Allow-Headers", "Accept, Accept-Language, Authorization, Cache-Control, Content-Disposition, Content-Encoding, Content-Language, Content-Length, Content-MD5, Content-Range, Content-Type, Date, Host, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, Origin, OriginToken, Pragma, Range, Slug, Transfer-Encoding, Want-Digest, X-MediaBrowser-Token, X-Emby-Authorization"); res.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS"); res.AddHeader("Access-Control-Allow-Origin", "*"); - var exception = dto as Exception; - - if (exception != null) + if (dto is Exception exception) { _logger.LogError(exception, "Error processing request for {RawUrl}", req.RawUrl); @@ -45,43 +42,26 @@ namespace Emby.Server.Implementations.HttpServer } } - var hasHeaders = dto as IHasHeaders; - - if (hasHeaders != null) + if (dto is IHasHeaders hasHeaders) { if (!hasHeaders.Headers.ContainsKey("Server")) { hasHeaders.Headers["Server"] = "Microsoft-NetCore/2.0, UPnP/1.0 DLNADOC/1.50"; - //hasHeaders.Headers["Server"] = "Mono-HTTPAPI/1.1"; } // Content length has to be explicitly set on on HttpListenerResponse or it won't be happy - string contentLength; - - if (hasHeaders.Headers.TryGetValue("Content-Length", out contentLength) && !string.IsNullOrEmpty(contentLength)) + if (hasHeaders.Headers.TryGetValue("Content-Length", out string contentLength) + && !string.IsNullOrEmpty(contentLength)) { var length = long.Parse(contentLength, UsCulture); if (length > 0) { res.SetContentLength(length); - - //var listenerResponse = res.OriginalResponse as HttpListenerResponse; - - //if (listenerResponse != null) - //{ - // // Disable chunked encoding. Technically this is only needed when using Content-Range, but - // // anytime we know the content length there's no need for it - // listenerResponse.SendChunked = false; - // return; - //} - res.SendChunked = false; } } } - - //res.KeepAlive = false; } /// diff --git a/Emby.Server.Implementations/Services/HttpResult.cs b/Emby.Server.Implementations/Services/HttpResult.cs index 91314c15ae..66813f4615 100644 --- a/Emby.Server.Implementations/Services/HttpResult.cs +++ b/Emby.Server.Implementations/Services/HttpResult.cs @@ -15,7 +15,6 @@ namespace Emby.Server.Implementations.Services public HttpResult(object response, string contentType, HttpStatusCode statusCode) { this.Headers = new Dictionary(); - this.Cookies = new List(); this.Response = response; this.ContentType = contentType; @@ -26,8 +25,6 @@ namespace Emby.Server.Implementations.Services public IDictionary Headers { get; private set; } - public List Cookies { get; private set; } - public int Status { get; set; } public HttpStatusCode StatusCode @@ -40,15 +37,16 @@ namespace Emby.Server.Implementations.Services public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken) { - var response = RequestContext != null ? RequestContext.Response : null; + var response = RequestContext == null ? null : RequestContext.Response; - var bytesResponse = this.Response as byte[]; - if (bytesResponse != null) + if (this.Response is byte[] bytesResponse) { var contentLength = bytesResponse.Length; if (response != null) + { response.SetContentLength(contentLength); + } if (contentLength > 0) { diff --git a/Emby.Server.Implementations/Services/RequestHelper.cs b/Emby.Server.Implementations/Services/RequestHelper.cs index 711ba8bbce..7d2fbc3e04 100644 --- a/Emby.Server.Implementations/Services/RequestHelper.cs +++ b/Emby.Server.Implementations/Services/RequestHelper.cs @@ -49,4 +49,4 @@ namespace Emby.Server.Implementations.Services } } -} \ No newline at end of file +} From d0980f0da57c14966e9e90b00f1880b1b82f4fc8 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Wed, 16 Jan 2019 19:13:13 +0100 Subject: [PATCH 2/2] Update HttpListenerHost.cs --- .../HttpServer/HttpListenerHost.cs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs index fb5f53367f..6b4f2bced5 100644 --- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -81,13 +81,7 @@ namespace Emby.Server.Implementations.HttpServer public string GlobalResponse { get; set; } - protected ILogger Logger - { - get - { - return _logger; - } - } + protected ILogger Logger => _logger; public object CreateInstance(Type type) {