Replace some todos with http extensions and prepare some socket work

pull/1010/head
Claus Vium 6 years ago
parent c3fa299acc
commit f3e7bc0573

@ -110,10 +110,12 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using ServiceStack;
using HttpResponse = MediaBrowser.Model.Net.HttpResponse;
using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate;
@ -642,7 +644,12 @@ namespace Emby.Server.Implementations
// await RunStartupTasks().ConfigureAwait(false);
// })
.UseUrls("http://localhost:8096")
.ConfigureServices(s => s.AddRouting())
.ConfigureServices(services =>
{
services.AddRouting();
services.AddHttpContextAccessor();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
})
.Configure( app =>
{
app.UseWebSockets(new WebSocketOptions {
@ -668,62 +675,63 @@ namespace Emby.Server.Implementations
var ctx = request.HttpContext;
if (ctx.WebSockets.IsWebSocketRequest)
{
try
{
var endpoint = ctx.Request.Path.ToString();
var url = ctx.Request.Path.ToString();
var queryString = new QueryParamCollection(request.Query);
var connectingArgs = new WebSocketConnectingEventArgs
{
Url = url,
QueryString = queryString,
Endpoint = endpoint
};
if (connectingArgs.AllowConnection)
{
Logger.LogDebug("Web socket connection allowed");
var webSocketContext = ctx.WebSockets.AcceptWebSocketAsync(null).Result;
//SharpWebSocket socket = new SharpWebSocket(webSocketContext, Logger);
//socket.ConnectAsServerAsync().ConfigureAwait(false);
// var connection = new WebSocketConnection(webSocketContext, e.Endpoint, _jsonSerializer, _logger)
// {
// OnReceive = ProcessWebSocketMessageReceived,
// Url = e.Url,
// QueryString = e.QueryString ?? new QueryParamCollection()
// };
//
// connection.Closed += Connection_Closed;
//
// lock (_webSocketConnections)
// {
// _webSocketConnections.Add(connection);
// }
//
// WebSocketConnected(new WebSocketConnectEventArgs
// {
// Url = url,
// QueryString = queryString,
// WebSocket = socket,
// Endpoint = endpoint
// });
await webSocketContext.ReceiveAsync(new ArraySegment<byte>(), CancellationToken.None).ConfigureAwait(false);
}
else
{
Logger.LogWarning("Web socket connection not allowed");
ctx.Response.StatusCode = 401;
}
}
catch (Exception ex)
{
ctx.Response.StatusCode = 500;
}
await ((HttpListenerHost)HttpServer)._websocketlistener.ProcessWebSocketRequest(ctx).ConfigureAwait(false);
// try
// {
// var endpoint = ctx.Request.Path.ToString();
// var url = ctx.Request.Path.ToString();
// var queryString = new QueryParamCollection(request.Query);
// var connectingArgs = new WebSocketConnectingEventArgs
// {
// Url = url,
// QueryString = queryString,
// Endpoint = endpoint
// };
// if (connectingArgs.AllowConnection)
// {
// Logger.LogDebug("Web socket connection allowed");
// var webSocketContext = ctx.WebSockets.AcceptWebSocketAsync(null).Result;
// //SharpWebSocket socket = new SharpWebSocket(webSocketContext, Logger);
// //socket.ConnectAsServerAsync().ConfigureAwait(false);
//// var connection = new WebSocketConnection(webSocketContext, e.Endpoint, _jsonSerializer, _logger)
//// {
//// OnReceive = ProcessWebSocketMessageReceived,
//// Url = e.Url,
//// QueryString = e.QueryString ?? new QueryParamCollection()
//// };
////
//// connection.Closed += Connection_Closed;
////
//// lock (_webSocketConnections)
//// {
//// _webSocketConnections.Add(connection);
//// }
////
//// WebSocketConnected(new WebSocketConnectEventArgs
//// {
//// Url = url,
//// QueryString = queryString,
//// WebSocket = socket,
//// Endpoint = endpoint
//// });
// await webSocketContext.ReceiveAsync(new ArraySegment<byte>(), CancellationToken.None).ConfigureAwait(false);
// }
// else
// {
// Logger.LogWarning("Web socket connection not allowed");
// ctx.Response.StatusCode = 401;
// }
// }
// catch (Exception ex)
// {
// ctx.Response.StatusCode = 500;
// }
}
var req = new WebSocketSharpRequest(request, response, request.Path, Logger);

@ -11,6 +11,7 @@ using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.Net;
using Emby.Server.Implementations.Services;
using Emby.Server.Implementations.SocketSharp;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
@ -73,6 +74,10 @@ namespace Emby.Server.Implementations.HttpServer
Instance = this;
ResponseFilters = Array.Empty<Action<IRequest, IResponse, object>>();
_websocketlistener = new WebSocketSharpListener(_logger)
{
WebSocketConnected = OnWebSocketConnected
};
}
public string GlobalResponse { get; set; }
@ -796,6 +801,8 @@ namespace Emby.Server.Implementations.HttpServer
private bool _disposed;
private readonly object _disposeLock = new object();
public WebSocketSharpListener _websocketlistener;
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;

@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
@ -8,6 +8,7 @@ using Emby.Server.Implementations.Net;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.SocketSharp
@ -120,14 +121,14 @@ using Microsoft.Extensions.Logging;
// return RequestHandler(httpReq, uri.OriginalString, uri.Host, uri.LocalPath, cancellationToken);
// }
private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
public async Task ProcessWebSocketRequest(HttpContext ctx)
{
try
{
var endpoint = ctx.Request.RemoteEndPoint.ToString();
var url = ctx.Request.RawUrl;
var endpoint = ctx.Connection.RemoteIpAddress.ToString();
var url = ctx.Request.GetDisplayUrl();
var queryString = new QueryParamCollection(ctx.Request.QueryString);
var queryString = new QueryParamCollection(ctx.Request.Query);
var connectingArgs = new WebSocketConnectingEventArgs
{
@ -142,40 +143,40 @@ using Microsoft.Extensions.Logging;
{
_logger.LogDebug("Web socket connection allowed");
var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);
var webSocketContext = await ctx.WebSockets.AcceptWebSocketAsync(null).ConfigureAwait(false);
if (WebSocketConnected != null)
{
SharpWebSocket socket = null; //new SharpWebSocket(webSocketContext.WebSocket, _logger);
await socket.ConnectAsServerAsync().ConfigureAwait(false);
WebSocketConnected(new WebSocketConnectEventArgs
{
Url = url,
QueryString = queryString,
WebSocket = socket,
Endpoint = endpoint
});
await ReceiveWebSocketAsync(ctx, socket).ConfigureAwait(false);
//SharpWebSocket socket = new SharpWebSocket(webSocketContext, _logger);
//await socket.ConnectAsServerAsync().ConfigureAwait(false);
//WebSocketConnected(new WebSocketConnectEventArgs
//{
// Url = url,
// QueryString = queryString,
// WebSocket = socket,
// Endpoint = endpoint
//});
//await ReceiveWebSocketAsync(ctx, socket).ConfigureAwait(false);
}
}
else
{
_logger.LogWarning("Web socket connection not allowed");
ctx.Response.StatusCode = 401;
ctx.Response.Close();
//ctx.Response.Close();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "AcceptWebSocketAsync error");
ctx.Response.StatusCode = 500;
ctx.Response.Close();
//ctx.Response.Close();
}
}
private async Task ReceiveWebSocketAsync(HttpListenerContext ctx, SharpWebSocket socket)
private async Task ReceiveWebSocketAsync(HttpContext ctx, SharpWebSocket socket)
{
try
{
@ -187,12 +188,11 @@ using Microsoft.Extensions.Logging;
}
}
private void TryClose(HttpListenerContext ctx, int statusCode)
private void TryClose(HttpContext ctx, int statusCode)
{
try
{
ctx.Response.StatusCode = statusCode;
ctx.Response.Close();
}
catch (ObjectDisposedException)
{

@ -7,6 +7,7 @@ using System.Text;
using Emby.Server.Implementations.HttpServer;
using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
@ -44,11 +45,11 @@ namespace Emby.Server.Implementations.SocketSharp
public object Dto { get; set; }
public string RawUrl => request.Path.ToUriComponent();
public string RawUrl => request.Path.ToString();
public string AbsoluteUri => request.Path.ToUriComponent().TrimEnd('/');
public string AbsoluteUri => request.GetDisplayUrl().TrimEnd('/');
public string UserHostAddress => "";
public string UserHostAddress => request.HttpContext.Connection.RemoteIpAddress.ToString();
public string XForwardedFor
=> StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-For"]) ? null : request.Headers["X-Forwarded-For"].ToString();
@ -66,7 +67,7 @@ namespace Emby.Server.Implementations.SocketSharp
remoteIp ??
(remoteIp = CheckBadChars(XForwardedFor) ??
NormalizeIp(CheckBadChars(XRealIp) ??
(string.IsNullOrEmpty(request.Host.Host) ? null : NormalizeIp(request.Host.Host))));
(string.IsNullOrEmpty(request.HttpContext.Connection.RemoteIpAddress.ToString()) ? null : NormalizeIp(request.HttpContext.Connection.RemoteIpAddress.ToString()))));
private static readonly char[] HttpTrimCharacters = new char[] { (char)0x09, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20 };
@ -199,7 +200,7 @@ namespace Emby.Server.Implementations.SocketSharp
const string serverDefaultContentType = "application/json";
var acceptContentTypes = httpReq.Headers.GetCommaSeparatedValues(HeaderNames.Accept); // TODO;
var acceptContentTypes = httpReq.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
string defaultContentType = null;
if (HasAnyOfContentTypes(httpReq, FormUrlEncoded, MultiPartFormData))
{
@ -448,7 +449,7 @@ namespace Emby.Server.Implementations.SocketSharp
private QueryParamCollection queryString;
public QueryParamCollection QueryString => queryString ?? (queryString = new QueryParamCollection(request.Query));
public bool IsLocal => true; // TODO
public bool IsLocal => string.Equals(request.HttpContext.Connection.LocalIpAddress.ToString(), request.HttpContext.Connection.RemoteIpAddress.ToString());
private string httpMethod;
public string HttpMethod =>

Loading…
Cancel
Save