update live stream management

This commit is contained in:
Luke Pulverenti
2016-10-07 11:08:13 -04:00
parent d22b7817a4
commit 50e6686987
53 changed files with 487 additions and 1078 deletions

View File

@@ -94,12 +94,12 @@ namespace MediaBrowser.Server.Implementations.HttpServer
// The Markdown feature causes slow startup times (5 mins+) on cold boots for some users
// Custom format allows images
HostConfig.Instance.EnableFeatures = Feature.Csv | Feature.Html | Feature.Json | Feature.Jsv | Feature.Metadata | Feature.Xml | Feature.CustomFormat;
HostConfig.Instance.EnableFeatures = Feature.Html | Feature.Json | Feature.CustomFormat;
container.Adapter = _containerAdapter;
Plugins.RemoveAll(x => x is NativeTypesFeature);
Plugins.Add(new SwaggerFeature());
//Plugins.Add(new SwaggerFeature());
Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization"));
//Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
@@ -546,8 +546,10 @@ namespace MediaBrowser.Server.Implementations.HttpServer
}
}
}
throw new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo);
else
{
httpRes.Close();
}
}
/// <summary>

View File

@@ -683,29 +683,6 @@ namespace MediaBrowser.Server.Implementations.HttpServer
}
}
/// <summary>
/// Gets the error result.
/// </summary>
/// <param name="statusCode">The status code.</param>
/// <param name="errorMessage">The error message.</param>
/// <param name="responseHeaders">The response headers.</param>
/// <returns>System.Object.</returns>
public void ThrowError(int statusCode, string errorMessage, IDictionary<string, string> responseHeaders = null)
{
var error = new HttpError
{
Status = statusCode,
ErrorCode = errorMessage
};
if (responseHeaders != null)
{
AddResponseHeaders(error, responseHeaders);
}
throw error;
}
public object GetAsyncStreamWriter(IAsyncStreamSource streamSource)
{
return new AsyncStreamWriter(streamSource);

View File

@@ -1,240 +0,0 @@
using MediaBrowser.Common.Events;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Logging;
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebSocketMessageType = MediaBrowser.Model.Net.WebSocketMessageType;
using WebSocketState = MediaBrowser.Model.Net.WebSocketState;
namespace MediaBrowser.Server.Implementations.HttpServer
{
/// <summary>
/// Class NativeWebSocket
/// </summary>
public class NativeWebSocket : IWebSocket
{
/// <summary>
/// The logger
/// </summary>
private readonly ILogger _logger;
public event EventHandler<EventArgs> Closed;
/// <summary>
/// Gets or sets the web socket.
/// </summary>
/// <value>The web socket.</value>
private System.Net.WebSockets.WebSocket WebSocket { get; set; }
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
/// <summary>
/// Initializes a new instance of the <see cref="NativeWebSocket" /> class.
/// </summary>
/// <param name="socket">The socket.</param>
/// <param name="logger">The logger.</param>
/// <exception cref="System.ArgumentNullException">socket</exception>
public NativeWebSocket(WebSocket socket, ILogger logger)
{
if (socket == null)
{
throw new ArgumentNullException("socket");
}
if (logger == null)
{
throw new ArgumentNullException("logger");
}
_logger = logger;
WebSocket = socket;
Receive();
}
/// <summary>
/// Gets or sets the state.
/// </summary>
/// <value>The state.</value>
public WebSocketState State
{
get
{
WebSocketState commonState;
if (!Enum.TryParse(WebSocket.State.ToString(), true, out commonState))
{
_logger.Warn("Unrecognized WebSocketState: {0}", WebSocket.State.ToString());
}
return commonState;
}
}
/// <summary>
/// Receives this instance.
/// </summary>
private async void Receive()
{
while (true)
{
byte[] bytes;
try
{
bytes = await ReceiveBytesAsync(_cancellationTokenSource.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
catch (WebSocketException ex)
{
_logger.ErrorException("Error receiving web socket message", ex);
break;
}
if (bytes == null)
{
// Connection closed
EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
break;
}
if (OnReceiveBytes != null)
{
OnReceiveBytes(bytes);
}
}
}
/// <summary>
/// Receives the async.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{WebSocketMessageInfo}.</returns>
/// <exception cref="System.Net.WebSockets.WebSocketException">Connection closed</exception>
private async Task<byte[]> ReceiveBytesAsync(CancellationToken cancellationToken)
{
var bytes = new byte[4096];
var buffer = new ArraySegment<byte>(bytes);
var result = await WebSocket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false);
if (result.CloseStatus.HasValue)
{
_logger.Info("Web socket connection closed by client. Reason: {0}", result.CloseStatus.Value);
return null;
}
return buffer.Array;
}
/// <summary>
/// Sends the async.
/// </summary>
/// <param name="bytes">The bytes.</param>
/// <param name="type">The type.</param>
/// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public Task SendAsync(byte[] bytes, WebSocketMessageType type, bool endOfMessage, CancellationToken cancellationToken)
{
System.Net.WebSockets.WebSocketMessageType nativeType;
if (!Enum.TryParse(type.ToString(), true, out nativeType))
{
_logger.Warn("Unrecognized WebSocketMessageType: {0}", type.ToString());
}
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cancellationTokenSource.Token);
return WebSocket.SendAsync(new ArraySegment<byte>(bytes), nativeType, true, linkedTokenSource.Token);
}
public Task SendAsync(byte[] bytes, bool endOfMessage, CancellationToken cancellationToken)
{
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cancellationTokenSource.Token);
return WebSocket.SendAsync(new ArraySegment<byte>(bytes), System.Net.WebSockets.WebSocketMessageType.Binary, true, linkedTokenSource.Token);
}
public Task SendAsync(string text, bool endOfMessage, CancellationToken cancellationToken)
{
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cancellationTokenSource.Token);
var bytes = Encoding.UTF8.GetBytes(text);
return WebSocket.SendAsync(new ArraySegment<byte>(bytes), System.Net.WebSockets.WebSocketMessageType.Text, true, linkedTokenSource.Token);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
if (dispose)
{
_cancellationTokenSource.Cancel();
WebSocket.Dispose();
}
}
/// <summary>
/// Gets or sets the receive action.
/// </summary>
/// <value>The receive action.</value>
public Action<byte[]> OnReceiveBytes { get; set; }
/// <summary>
/// Gets or sets the on receive.
/// </summary>
/// <value>The on receive.</value>
public Action<string> OnReceive { get; set; }
/// <summary>
/// The _supports native web socket
/// </summary>
private static bool? _supportsNativeWebSocket;
/// <summary>
/// Gets a value indicating whether [supports web sockets].
/// </summary>
/// <value><c>true</c> if [supports web sockets]; otherwise, <c>false</c>.</value>
public static bool IsSupported
{
get
{
if (!_supportsNativeWebSocket.HasValue)
{
try
{
new ClientWebSocket();
_supportsNativeWebSocket = true;
}
catch (PlatformNotSupportedException)
{
_supportsNativeWebSocket = false;
}
}
return _supportsNativeWebSocket.Value;
}
}
}
}

View File

@@ -191,15 +191,6 @@ namespace MediaBrowser.Server.Implementations.HttpServer
}
}
}
catch (IOException)
{
throw;
}
catch (Exception ex)
{
_logger.ErrorException("Error in range request writer", ex);
throw;
}
finally
{
if (OnComplete != null)
@@ -251,15 +242,6 @@ namespace MediaBrowser.Server.Implementations.HttpServer
}
}
}
catch (IOException ex)
{
throw;
}
catch (Exception ex)
{
_logger.ErrorException("Error in range request writer", ex);
throw;
}
finally
{
if (OnComplete != null)

View File

@@ -81,20 +81,12 @@ namespace MediaBrowser.Server.Implementations.HttpServer.SocketSharp
public void Write(string text)
{
try
{
var bOutput = System.Text.Encoding.UTF8.GetBytes(text);
response.ContentLength64 = bOutput.Length;
var bOutput = System.Text.Encoding.UTF8.GetBytes(text);
response.ContentLength64 = bOutput.Length;
var outputStream = response.OutputStream;
outputStream.Write(bOutput, 0, bOutput.Length);
Close();
}
catch (Exception ex)
{
_logger.ErrorException("Could not WriteTextToResponse: " + ex.Message, ex);
throw;
}
var outputStream = response.OutputStream;
outputStream.Write(bOutput, 0, bOutput.Length);
Close();
}
public void Close()