jellyfin/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs

290 lines
9.1 KiB
C#
Raw Normal View History

2015-03-09 00:36:02 +00:00
using System.Text;
using MediaBrowser.Controller.Net;
using Microsoft.Extensions.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;
using System.Threading;
using System.Threading.Tasks;
2016-10-25 19:02:04 +00:00
using MediaBrowser.Model.Services;
2016-11-08 18:44:23 +00:00
using MediaBrowser.Model.Text;
2018-09-12 17:26:21 +00:00
using System.Net.WebSockets;
using Emby.Server.Implementations.Net;
2013-02-21 01:33:05 +00:00
2018-09-12 17:26:21 +00:00
namespace Emby.Server.Implementations.HttpServer
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;
2016-10-07 15:08:13 +00:00
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 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>
2018-09-12 17:26:21 +00:00
public Func<WebSocketMessageInfo, Task> 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>
2016-10-25 19:02:04 +00:00
public QueryParamCollection QueryString { get; set; }
2016-11-08 18:44:23 +00:00
private readonly ITextEncoding _textEncoding;
2016-10-06 18:55:01 +00:00
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>
2018-09-12 17:26:21 +00:00
public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger, ITextEncoding textEncoding)
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;
2018-09-12 17:26:21 +00:00
var memorySocket = socket as IMemoryWebSocket;
if (memorySocket != null)
{
memorySocket.OnReceiveMemoryBytes = OnReceiveInternal;
}
2013-02-21 01:33:05 +00:00
RemoteEndPoint = remoteEndPoint;
2013-02-21 21:06:23 +00:00
_logger = logger;
2016-11-03 22:53:02 +00:00
_textEncoding = textEncoding;
2014-05-17 18:37:40 +00:00
socket.Closed += socket_Closed;
}
void socket_Closed(object sender, EventArgs e)
{
Closed?.Invoke(this, EventArgs.Empty);
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;
}
2017-04-18 05:53:39 +00:00
2017-09-04 01:24:20 +00:00
var charset = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, null, false);
2015-03-09 00:36:02 +00:00
if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
{
2016-11-03 22:53:02 +00:00
OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
2015-03-09 00:36:02 +00:00
}
else
{
2016-11-08 18:44:23 +00:00
OnReceiveInternal(_textEncoding.GetASCIIEncoding().GetString(bytes, 0, bytes.Length));
2015-03-09 00:36:02 +00:00
}
}
2013-02-21 01:33:05 +00:00
2018-09-12 17:26:21 +00:00
/// <summary>
/// Called when [receive].
/// </summary>
/// <param name="bytes">The bytes.</param>
private void OnReceiveInternal(Memory<byte> memory, int length)
{
LastActivityDate = DateTime.UtcNow;
if (OnReceive == null)
{
return;
}
var bytes = memory.Slice(0, length).ToArray();
var charset = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, null, false);
if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
{
OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
}
else
{
OnReceiveInternal(_textEncoding.GetASCIIEncoding().GetString(bytes, 0, bytes.Length));
}
}
private void OnReceiveInternal(string message)
{
LastActivityDate = DateTime.UtcNow;
if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
{
2015-06-07 21:21:30 +00:00
// This info is useful sometimes but also clogs up the log
2018-12-20 12:11:26 +00:00
_logger.LogDebug("Received web socket message that is not a json structure: {message}", 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)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error processing web socket message");
}
}
2016-10-07 15:08:13 +00:00
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>
2016-10-07 15:08:13 +00:00
public 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();
2016-10-07 15:08:13 +00:00
return _socket.SendAsync(buffer, true, cancellationToken);
2013-02-21 01:33:05 +00:00
}
2016-10-07 15:08:13 +00:00
public Task SendAsync(string text, CancellationToken cancellationToken)
2013-02-21 01:33:05 +00:00
{
2018-09-12 17:26:21 +00:00
if (string.IsNullOrEmpty(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();
2016-10-07 15:08:13 +00:00
return _socket.SendAsync(text, true, cancellationToken);
2013-02-21 01:33:05 +00:00
}
/// <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);
}
/// <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)
{
_socket.Dispose();
}
}
}
}