jellyfin-server/MediaBrowser.Server.Implementations/ServerManager/WebSocketConnection.cs

338 lines
11 KiB
C#
Raw Normal View History

2015-03-09 00:36:02 +00:00
using System.Text;
using MediaBrowser.Common.Events;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Net;
2013-02-24 21:53:54 +00:00
using MediaBrowser.Model.Serialization;
2013-02-21 01:33:05 +00:00
using System;
2015-03-08 19:48:30 +00:00
using System.Collections.Specialized;
2013-02-25 00:13:45 +00:00
using System.IO;
2013-02-21 01:33:05 +00:00
using System.Threading;
using System.Threading.Tasks;
2015-03-09 00:36:02 +00:00
using UniversalDetector;
2013-02-21 01:33:05 +00:00
2013-03-07 05:34:00 +00:00
namespace MediaBrowser.Server.Implementations.ServerManager
2013-02-21 01:33:05 +00:00
{
/// <summary>
/// Class WebSocketConnection
/// </summary>
public class WebSocketConnection : IWebSocketConnection
2013-02-21 01:33:05 +00:00
{
2014-05-17 18:37:40 +00:00
public event EventHandler<EventArgs> Closed;
2013-02-21 01:33:05 +00:00
/// <summary>
/// The _socket
/// </summary>
private readonly IWebSocket _socket;
/// <summary>
/// The _remote end point
/// </summary>
public string RemoteEndPoint { get; private set; }
2013-02-21 01:33:05 +00:00
/// <summary>
/// The _cancellation token source
/// </summary>
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
/// <summary>
/// The _send semaphore
/// </summary>
2013-05-10 12:18:07 +00:00
private readonly SemaphoreSlim _sendSemaphore = new SemaphoreSlim(1, 1);
2013-02-21 01:33:05 +00:00
/// <summary>
/// The logger
/// </summary>
2013-02-21 21:06:23 +00:00
private readonly ILogger _logger;
2013-02-21 01:33:05 +00:00
2013-02-24 21:53:54 +00:00
/// <summary>
/// The _json serializer
/// </summary>
private readonly IJsonSerializer _jsonSerializer;
/// <summary>
/// Gets or sets the receive action.
/// </summary>
/// <value>The receive action.</value>
public Action<WebSocketMessageInfo> OnReceive { get; set; }
2013-05-26 00:53:51 +00:00
/// <summary>
/// Gets the last activity date.
/// </summary>
/// <value>The last activity date.</value>
public DateTime LastActivityDate { get; private set; }
2013-10-03 01:22:50 +00:00
/// <summary>
/// Gets the id.
/// </summary>
/// <value>The id.</value>
public Guid Id { get; private set; }
2015-03-08 19:48:30 +00:00
/// <summary>
/// Gets or sets the URL.
/// </summary>
/// <value>The URL.</value>
public string Url { get; set; }
/// <summary>
/// Gets or sets the query string.
/// </summary>
/// <value>The query string.</value>
public NameValueCollection QueryString { get; set; }
2013-02-21 01:33:05 +00:00
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
/// </summary>
/// <param name="socket">The socket.</param>
/// <param name="remoteEndPoint">The remote end point.</param>
2013-02-24 21:53:54 +00:00
/// <param name="jsonSerializer">The json serializer.</param>
/// <param name="logger">The logger.</param>
2013-02-21 01:33:05 +00:00
/// <exception cref="System.ArgumentNullException">socket</exception>
public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger)
2013-02-21 01:33:05 +00:00
{
if (socket == null)
{
throw new ArgumentNullException("socket");
}
if (string.IsNullOrEmpty(remoteEndPoint))
2013-02-21 01:33:05 +00:00
{
throw new ArgumentNullException("remoteEndPoint");
}
2013-02-24 21:53:54 +00:00
if (jsonSerializer == null)
{
throw new ArgumentNullException("jsonSerializer");
}
2013-02-21 21:06:23 +00:00
if (logger == null)
{
throw new ArgumentNullException("logger");
}
2013-02-21 01:33:05 +00:00
2013-10-03 01:22:50 +00:00
Id = Guid.NewGuid();
2013-02-24 21:53:54 +00:00
_jsonSerializer = jsonSerializer;
2013-02-21 01:33:05 +00:00
_socket = socket;
_socket.OnReceiveBytes = OnReceiveInternal;
_socket.OnReceive = OnReceiveInternal;
2013-02-21 01:33:05 +00:00
RemoteEndPoint = remoteEndPoint;
2013-02-21 21:06:23 +00:00
_logger = logger;
2014-05-17 18:37:40 +00:00
socket.Closed += socket_Closed;
}
void socket_Closed(object sender, EventArgs e)
{
EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
2013-02-21 01:33:05 +00:00
}
/// <summary>
/// Called when [receive].
/// </summary>
2013-02-24 21:53:54 +00:00
/// <param name="bytes">The bytes.</param>
private void OnReceiveInternal(byte[] bytes)
2013-02-21 01:33:05 +00:00
{
2013-05-26 00:53:51 +00:00
LastActivityDate = DateTime.UtcNow;
if (OnReceive == null)
{
return;
}
2015-03-09 00:36:02 +00:00
var charset = DetectCharset(bytes);
if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
{
OnReceiveInternal(Encoding.UTF8.GetString(bytes));
}
else
{
OnReceiveInternal(Encoding.ASCII.GetString(bytes));
}
}
private string DetectCharset(byte[] bytes)
{
2013-02-21 01:33:05 +00:00
try
{
2015-03-09 00:36:02 +00:00
using (var ms = new MemoryStream(bytes))
2013-02-24 21:53:54 +00:00
{
2015-03-09 00:36:02 +00:00
var detector = new CharsetDetector();
detector.Feed(ms);
detector.DataEnd();
2013-05-10 12:18:07 +00:00
2015-03-09 00:36:02 +00:00
var charset = detector.Charset;
2013-02-24 21:53:54 +00:00
2015-03-09 00:36:02 +00:00
if (!string.IsNullOrWhiteSpace(charset))
{
//_logger.Debug("UniversalDetector detected charset {0}", charset);
}
2013-02-21 01:33:05 +00:00
2015-03-09 00:36:02 +00:00
return charset;
}
2013-02-21 01:33:05 +00:00
}
2015-03-09 00:36:02 +00:00
catch (IOException ex)
2013-02-21 01:33:05 +00:00
{
2015-03-09 00:36:02 +00:00
_logger.ErrorException("Error attempting to determine web socket message charset", ex);
2013-02-21 01:33:05 +00:00
}
2015-03-09 00:36:02 +00:00
return null;
2013-02-21 01:33:05 +00:00
}
private void OnReceiveInternal(string message)
{
LastActivityDate = DateTime.UtcNow;
if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
{
_logger.Error("Received web socket message that is not a json structure: " + message);
return;
}
if (OnReceive == null)
{
return;
}
try
{
var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
var info = new WebSocketMessageInfo
{
MessageType = stub.MessageType,
2014-04-06 17:53:23 +00:00
Data = stub.Data == null ? null : stub.Data.ToString(),
Connection = this
};
OnReceive(info);
}
catch (Exception ex)
{
_logger.ErrorException("Error processing web socket message", ex);
}
}
2013-02-21 01:33:05 +00:00
/// <summary>
/// Sends a message asynchronously.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="message">The message.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">message</exception>
public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
{
if (message == null)
{
throw new ArgumentNullException("message");
}
2013-02-24 21:53:54 +00:00
2014-07-20 04:46:29 +00:00
var json = _jsonSerializer.SerializeToString(message);
2013-02-21 01:33:05 +00:00
2014-07-20 04:46:29 +00:00
return SendAsync(json, cancellationToken);
2013-02-21 01:33:05 +00:00
}
/// <summary>
/// Sends a message asynchronously.
/// </summary>
/// <param name="buffer">The buffer.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
2014-07-20 04:46:29 +00:00
public async Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
2013-02-21 01:33:05 +00:00
{
2014-07-20 04:46:29 +00:00
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
cancellationToken.ThrowIfCancellationRequested();
// Per msdn docs, attempting to send simultaneous messages will result in one failing.
// This should help us workaround that and ensure all messages get sent
await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
await _socket.SendAsync(buffer, true, cancellationToken);
}
catch (OperationCanceledException)
{
_logger.Info("WebSocket message to {0} was cancelled", RemoteEndPoint);
throw;
}
catch (Exception ex)
{
_logger.ErrorException("Error sending WebSocket message {0}", ex, RemoteEndPoint);
throw;
}
finally
{
_sendSemaphore.Release();
}
2013-02-21 01:33:05 +00:00
}
2014-07-20 04:46:29 +00:00
public async Task SendAsync(string text, CancellationToken cancellationToken)
2013-02-21 01:33:05 +00:00
{
2014-07-20 04:46:29 +00:00
if (string.IsNullOrWhiteSpace(text))
2013-02-21 01:33:05 +00:00
{
2014-07-20 04:46:29 +00:00
throw new ArgumentNullException("text");
2013-02-21 01:33:05 +00:00
}
cancellationToken.ThrowIfCancellationRequested();
// Per msdn docs, attempting to send simultaneous messages will result in one failing.
// This should help us workaround that and ensure all messages get sent
await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
2014-07-20 04:46:29 +00:00
await _socket.SendAsync(text, true, cancellationToken);
2013-02-21 01:33:05 +00:00
}
catch (OperationCanceledException)
{
2013-02-21 21:06:23 +00:00
_logger.Info("WebSocket message to {0} was cancelled", RemoteEndPoint);
2013-02-21 01:33:05 +00:00
throw;
}
catch (Exception ex)
{
2013-02-21 21:06:23 +00:00
_logger.ErrorException("Error sending WebSocket message {0}", ex, RemoteEndPoint);
2013-02-21 01:33:05 +00:00
throw;
}
finally
{
_sendSemaphore.Release();
}
}
/// <summary>
/// Gets the state.
/// </summary>
/// <value>The state.</value>
public WebSocketState State
{
get { return _socket.State; }
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <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.Dispose();
_socket.Dispose();
}
}
}
}