Example #1
0
        /// <summary>
        /// Overridable method that can be used to implement a custom hnandler
        /// </summary>
        /// <param name="context"></param>
        protected Task ProcessRequestAsync(HttpListenerContext context)
        {
            if (string.IsNullOrEmpty(context.Request.RawUrl))
            {
                return(((object)null).AsTaskResult());
            }

            var operationName = context.Request.GetOperationName();

            var httpReq = context.ToRequest(operationName);
            var httpRes = httpReq.Response;
            var handler = HttpHandlerFactory.GetHandler(httpReq);

            var serviceStackHandler = handler as IServiceStackHandler;

            if (serviceStackHandler != null)
            {
                var restHandler = serviceStackHandler as RestHandler;
                if (restHandler != null)
                {
                    httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
                }

                var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
                task.ContinueWith(x => httpRes.Close());

                return(task);
            }

            return(new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
                   .AsTaskException());
        }
        /// <summary>
        /// When overrided in the sub class, which can be used to implement a custom hnandler
        /// </summary>
        /// <param name="context"></param>

        protected virtual Task ProcessRequestAsync(HttpListenerContext context)
        {
            if (string.IsNullOrEmpty(context.Request.RawUrl))
            {
                return(TypeConstants.EmptyTask);
            }

            RequestContext.Instance.StartRequestContext();

            var operationName = context.Request.GetOperationName().UrlDecode();

            var httpReq = context.ToRequest(operationName);
            var httpRes = httpReq.Response;

            var handler = HttpHandlerFactory.GetHandler(httpReq);

            var serviceStackHandler = handler as IServiceStackHandler;

            if (serviceStackHandler == null)
            {
                throw new NotImplementedException($"Cannot execute handler: {handler} at PathInfo: {httpReq.PathInfo}");
            }

            var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);

            return(HostContext.Async.ContinueWith(httpReq, task, x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent));
            //Matches Exceptions handled in HttpListenerBase.InitTask()
        }
        public void GetHandlerReturnsNull()
        {
            var dependancyResolverMock = new Mock <IDependencyResolver>();
            var handler = _fixture.Create <PlanningPokerWebSocketHandler>();

            dependancyResolverMock.Setup(x => x.Resolve <PlanningPokerWebSocketHandler>()).Returns(handler);
            var factory = new HttpHandlerFactory(dependancyResolverMock.Object);
            var result  = factory.GetHandler(null, "get", "/", "");

            Assert.IsNull(result);
        }
        /// <summary>
        /// Overridable method that can be used to implement a custom hnandler
        /// </summary>
        /// <param name="httpReq">The HTTP req.</param>
        /// <param name="url">The URL.</param>
        /// <returns>Task.</returns>
        protected Task RequestHandler(IHttpRequest httpReq, Uri url)
        {
            var date = DateTime.Now;

            var httpRes = httpReq.Response;

            var operationName = httpReq.OperationName;
            var localPath     = url.LocalPath;

            if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl(DefaultRedirectPath);
                return(Task.FromResult(true));
            }
            if (string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl("mediabrowser/" + DefaultRedirectPath);
                return(Task.FromResult(true));
            }
            if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl("emby/" + DefaultRedirectPath);
                return(Task.FromResult(true));
            }
            if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl(DefaultRedirectPath);
                return(Task.FromResult(true));
            }
            if (string.IsNullOrEmpty(localPath))
            {
                httpRes.RedirectToUrl("/" + DefaultRedirectPath);
                return(Task.FromResult(true));
            }

            var handler = HttpHandlerFactory.GetHandler(httpReq);

            var remoteIp = httpReq.RemoteIp;

            var serviceStackHandler = handler as IServiceStackHandler;

            if (serviceStackHandler != null)
            {
                var restHandler = serviceStackHandler as RestHandler;
                if (restHandler != null)
                {
                    httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
                }

                var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);

                task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
                //Matches Exceptions handled in HttpListenerBase.InitTask()

                var urlString = url.ToString();

                task.ContinueWith(x =>
                {
                    var statusCode = httpRes.StatusCode;

                    var duration = DateTime.Now - date;

                    LoggerUtils.LogResponse(_logger, statusCode, urlString, remoteIp, duration);
                }, TaskContinuationOptions.None);
                return(task);
            }

            return(new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
                   .AsTaskException());
        }
Example #5
0
        /// <summary>
        /// Overridable method that can be used to implement a custom hnandler
        /// </summary>
        /// <param name="httpReq">The HTTP req.</param>
        /// <param name="url">The URL.</param>
        /// <returns>Task.</returns>
        protected async Task RequestHandler(IHttpRequest httpReq, Uri url)
        {
            var    date      = DateTime.Now;
            var    httpRes   = httpReq.Response;
            bool   enableLog = false;
            string urlToLog  = null;
            string remoteIp  = null;

            try
            {
                if (_disposed)
                {
                    httpRes.StatusCode  = 503;
                    httpRes.ContentType = "text/plain";
                    Write(httpRes, "Server shutting down");
                    return;
                }

                if (!ValidateHost(url))
                {
                    httpRes.StatusCode  = 400;
                    httpRes.ContentType = "text/plain";
                    Write(httpRes, "Invalid host");
                    return;
                }

                if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
                {
                    httpRes.StatusCode = 200;
                    httpRes.AddHeader("Access-Control-Allow-Origin", "*");
                    httpRes.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
                    httpRes.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization");
                    httpRes.ContentType = "text/plain";
                    Write(httpRes, string.Empty);
                    return;
                }

                var operationName = httpReq.OperationName;
                var localPath     = url.LocalPath;

                var urlString = url.OriginalString;
                enableLog = EnableLogging(urlString, localPath);
                urlToLog  = urlString;

                if (enableLog)
                {
                    urlToLog = GetUrlToLog(urlString);
                    remoteIp = httpReq.RemoteIp;

                    LoggerUtils.LogRequest(_logger, urlToLog, httpReq.HttpMethod, httpReq.UserAgent);
                }

                if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase))
                {
                    RedirectToUrl(httpRes, DefaultRedirectPath);
                    return;
                }
                if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
                {
                    RedirectToUrl(httpRes, "emby/" + DefaultRedirectPath);
                    return;
                }

                if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) ||
                    localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    httpRes.StatusCode  = 200;
                    httpRes.ContentType = "text/html";
                    var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
                                 .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);

                    if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
                    {
                        Write(httpRes,
                              "<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" +
                              newUrl + "\">" + newUrl + "</a></body></html>");
                        return;
                    }
                }

                if (localPath.IndexOf("dashboard/", StringComparison.OrdinalIgnoreCase) != -1 &&
                    localPath.IndexOf("web/dashboard", StringComparison.OrdinalIgnoreCase) == -1)
                {
                    httpRes.StatusCode  = 200;
                    httpRes.ContentType = "text/html";
                    var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
                                 .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);

                    if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
                    {
                        Write(httpRes,
                              "<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" +
                              newUrl + "\">" + newUrl + "</a></body></html>");
                        return;
                    }
                }

                if (string.Equals(localPath, "/web", StringComparison.OrdinalIgnoreCase))
                {
                    RedirectToUrl(httpRes, DefaultRedirectPath);
                    return;
                }
                if (string.Equals(localPath, "/web/", StringComparison.OrdinalIgnoreCase))
                {
                    RedirectToUrl(httpRes, "../" + DefaultRedirectPath);
                    return;
                }
                if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
                {
                    RedirectToUrl(httpRes, DefaultRedirectPath);
                    return;
                }
                if (string.IsNullOrEmpty(localPath))
                {
                    RedirectToUrl(httpRes, "/" + DefaultRedirectPath);
                    return;
                }

                if (string.Equals(localPath, "/emby/pin", StringComparison.OrdinalIgnoreCase))
                {
                    RedirectToUrl(httpRes, "web/pin.html");
                    return;
                }

                if (!string.IsNullOrWhiteSpace(GlobalResponse))
                {
                    httpRes.StatusCode  = 503;
                    httpRes.ContentType = "text/html";
                    Write(httpRes, GlobalResponse);
                    return;
                }

                var handler = HttpHandlerFactory.GetHandler(httpReq, _logger);

                if (handler != null)
                {
                    await handler.ProcessRequestAsync(httpReq, httpRes, operationName).ConfigureAwait(false);
                }
                else
                {
                    ErrorHandler(new FileNotFoundException(), httpReq);
                }
            }
            catch (OperationCanceledException ex)
            {
                ErrorHandler(ex, httpReq, false);
            }
            catch (Exception ex)
            {
                ErrorHandler(ex, httpReq);
            }
            finally
            {
                httpRes.Close();

                if (enableLog)
                {
                    var statusCode = httpRes.StatusCode;

                    var duration = DateTime.Now - date;

                    LoggerUtils.LogResponse(_logger, statusCode, urlToLog, remoteIp, duration);
                }
            }
        }
Example #6
0
        /// <summary>
        /// Overridable method that can be used to implement a custom hnandler
        /// </summary>
        /// <param name="httpReq">The HTTP req.</param>
        /// <param name="url">The URL.</param>
        /// <returns>Task.</returns>
        protected Task RequestHandler(IHttpRequest httpReq, Uri url)
        {
            var date = DateTime.Now;

            var httpRes = httpReq.Response;

            var operationName = httpReq.OperationName;
            var localPath     = url.LocalPath;

            var urlString = url.OriginalString;
            var enableLog = EnableLogging(urlString, localPath);
            var urlToLog  = urlString;

            if (enableLog)
            {
                urlToLog = GetUrlToLog(urlString);
                LoggerUtils.LogRequest(_logger, urlToLog, httpReq.HttpMethod, httpReq.UserAgent);
            }

            if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl(DefaultRedirectPath);
                return(Task.FromResult(true));
            }
            if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl("emby/" + DefaultRedirectPath);
                return(Task.FromResult(true));
            }

            if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) ||
                localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1 ||
                localPath.IndexOf("dashboard/", StringComparison.OrdinalIgnoreCase) != -1)
            {
                httpRes.StatusCode  = 200;
                httpRes.ContentType = "text/html";
                var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
                             .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);

                if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
                {
                    httpRes.Write("<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" + newUrl + "\">" + newUrl + "</a></body></html>");

                    httpRes.Close();
                    return(Task.FromResult(true));
                }
            }

            if (string.Equals(localPath, "/web", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl(DefaultRedirectPath);
                return(Task.FromResult(true));
            }
            if (string.Equals(localPath, "/web/", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl("../" + DefaultRedirectPath);
                return(Task.FromResult(true));
            }
            if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl(DefaultRedirectPath);
                return(Task.FromResult(true));
            }
            if (string.IsNullOrEmpty(localPath))
            {
                httpRes.RedirectToUrl("/" + DefaultRedirectPath);
                return(Task.FromResult(true));
            }

            if (string.Equals(localPath, "/emby/pin", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl("web/pin.html");
                return(Task.FromResult(true));
            }

            if (!string.IsNullOrWhiteSpace(GlobalResponse))
            {
                httpRes.StatusCode  = 503;
                httpRes.ContentType = "text/html";
                httpRes.Write(GlobalResponse);

                httpRes.Close();
                return(Task.FromResult(true));
            }

            var handler = HttpHandlerFactory.GetHandler(httpReq);

            var remoteIp = httpReq.RemoteIp;

            var serviceStackHandler = handler as IServiceStackHandler;

            if (serviceStackHandler != null)
            {
                var restHandler = serviceStackHandler as RestHandler;
                if (restHandler != null)
                {
                    httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
                }

                var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);

                task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
                //Matches Exceptions handled in HttpListenerBase.InitTask()

                task.ContinueWith(x =>
                {
                    var statusCode = httpRes.StatusCode;

                    var duration = DateTime.Now - date;

                    if (enableLog)
                    {
                        LoggerUtils.LogResponse(_logger, statusCode, urlToLog, remoteIp, duration);
                    }
                }, TaskContinuationOptions.None);
                return(task);
            }

            return(new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
                   .AsTaskException());
        }
Example #7
0
        /// <summary>
        /// Overridable method that can be used to implement a custom hnandler
        /// </summary>
        /// <param name="httpReq">The HTTP req.</param>
        /// <param name="url">The URL.</param>
        /// <returns>Task.</returns>
        protected async Task RequestHandler(IHttpRequest httpReq, Uri url)
        {
            var date = DateTime.Now;

            var httpRes = httpReq.Response;

            if (_disposed)
            {
                httpRes.StatusCode = 503;
                httpRes.Close();
                return;
            }

            if (!ValidateHost(url))
            {
                httpRes.StatusCode  = 400;
                httpRes.ContentType = "text/plain";
                httpRes.Write("Invalid host");

                httpRes.Close();
                return;
            }

            if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.StatusCode = 200;
                httpRes.AddHeader("Access-Control-Allow-Origin", "*");
                httpRes.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
                httpRes.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization");
                httpRes.ContentType = "text/html";

                httpRes.Close();
            }

            var operationName = httpReq.OperationName;
            var localPath     = url.LocalPath;

            var urlString = url.OriginalString;
            var enableLog = EnableLogging(urlString, localPath);
            var urlToLog  = urlString;

            if (enableLog)
            {
                urlToLog = GetUrlToLog(urlString);
                LoggerUtils.LogRequest(_logger, urlToLog, httpReq.HttpMethod, httpReq.UserAgent);
            }

            if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl(DefaultRedirectPath);
                return;
            }
            if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl("emby/" + DefaultRedirectPath);
                return;
            }

            if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) ||
                localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1)
            {
                httpRes.StatusCode  = 200;
                httpRes.ContentType = "text/html";
                var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
                             .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);

                if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
                {
                    httpRes.Write("<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" + newUrl + "\">" + newUrl + "</a></body></html>");

                    httpRes.Close();
                    return;
                }
            }

            if (localPath.IndexOf("dashboard/", StringComparison.OrdinalIgnoreCase) != -1 &&
                localPath.IndexOf("web/dashboard", StringComparison.OrdinalIgnoreCase) == -1)
            {
                httpRes.StatusCode  = 200;
                httpRes.ContentType = "text/html";
                var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
                             .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);

                if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
                {
                    httpRes.Write("<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" + newUrl + "\">" + newUrl + "</a></body></html>");

                    httpRes.Close();
                    return;
                }
            }

            if (string.Equals(localPath, "/web", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl(DefaultRedirectPath);
                return;
            }
            if (string.Equals(localPath, "/web/", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl("../" + DefaultRedirectPath);
                return;
            }
            if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl(DefaultRedirectPath);
                return;
            }
            if (string.IsNullOrEmpty(localPath))
            {
                httpRes.RedirectToUrl("/" + DefaultRedirectPath);
                return;
            }

            if (string.Equals(localPath, "/emby/pin", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.RedirectToUrl("web/pin.html");
                return;
            }

            if (!string.IsNullOrWhiteSpace(GlobalResponse))
            {
                httpRes.StatusCode  = 503;
                httpRes.ContentType = "text/html";
                httpRes.Write(GlobalResponse);

                httpRes.Close();
                return;
            }

            var handler = HttpHandlerFactory.GetHandler(httpReq);

            var remoteIp = httpReq.RemoteIp;

            var serviceStackHandler = handler as IServiceStackHandler;

            if (serviceStackHandler != null)
            {
                var restHandler = serviceStackHandler as RestHandler;
                if (restHandler != null)
                {
                    httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
                }

                try
                {
                    await serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName).ConfigureAwait(false);
                }
                finally
                {
                    httpRes.Close();
                    var statusCode = httpRes.StatusCode;

                    var duration = DateTime.Now - date;

                    if (enableLog)
                    {
                        LoggerUtils.LogResponse(_logger, statusCode, urlToLog, remoteIp, duration);
                    }
                }
            }

            throw new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo);
        }