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

256 lines
7.8 KiB
C#
Raw Normal View History

using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.Net;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Net;
2013-02-24 21:53:54 +00:00
using MediaBrowser.Model.Serialization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using UtfUnknown;
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>
2019-11-01 17:38:54 +00:00
/// Class WebSocketConnection.
2013-02-21 01:33:05 +00:00
/// </summary>
public class WebSocketConnection : IWebSocketConnection
2013-02-21 01:33:05 +00:00
{
/// <summary>
2019-11-01 17:38:54 +00:00
/// The logger.
2013-02-21 01:33:05 +00:00
/// </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.
2013-02-24 21:53:54 +00:00
/// </summary>
private readonly IJsonSerializer _jsonSerializer;
/// <summary>
/// The socket.
2013-10-03 01:22:50 +00:00
/// </summary>
2019-11-01 17:38:54 +00:00
private readonly IWebSocket _socket;
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>
2019-01-13 20:37:13 +00:00
/// <exception cref="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(nameof(socket));
2013-02-21 01:33:05 +00:00
}
2019-11-01 17:38:54 +00:00
if (string.IsNullOrEmpty(remoteEndPoint))
2013-02-21 01:33:05 +00:00
{
throw new ArgumentNullException(nameof(remoteEndPoint));
2013-02-21 01:33:05 +00:00
}
2019-11-01 17:38:54 +00:00
2013-02-24 21:53:54 +00:00
if (jsonSerializer == null)
{
throw new ArgumentNullException(nameof(jsonSerializer));
2013-02-24 21:53:54 +00:00
}
2019-11-01 17:38:54 +00:00
2013-02-21 21:06:23 +00:00
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
2013-02-21 21:06:23 +00:00
}
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
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
2019-11-01 17:38:54 +00:00
socket.Closed += OnSocketClosed;
2014-05-17 18:37:40 +00:00
}
2019-11-01 17:38:54 +00:00
/// <inheritdoc />
public event EventHandler<EventArgs> Closed;
/// <summary>
/// Gets or sets the remote end point.
2019-11-01 17:38:54 +00:00
/// </summary>
public string RemoteEndPoint { get; private set; }
/// <summary>
/// Gets or sets the receive action.
/// </summary>
/// <value>The receive action.</value>
public Func<WebSocketMessageInfo, Task> OnReceive { get; set; }
/// <summary>
/// Gets the last activity date.
/// </summary>
/// <value>The last activity date.</value>
public DateTime LastActivityDate { get; private set; }
/// <summary>
/// Gets the id.
/// </summary>
/// <value>The id.</value>
public Guid Id { get; private set; }
/// <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 IQueryCollection QueryString { get; set; }
/// <summary>
/// Gets the state.
/// </summary>
/// <value>The state.</value>
public WebSocketState State => _socket.State;
void OnSocketClosed(object sender, EventArgs e)
2014-05-17 18:37:40 +00:00
{
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;
}
var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName;
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
{
OnReceiveInternal(Encoding.ASCII.GetString(bytes, 0, bytes.Length));
2015-03-09 00:36:02 +00:00
}
}
2013-02-21 01:33:05 +00:00
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,
Data = stub.Data?.ToString(),
2014-04-06 17:53:23 +00:00
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>
2019-01-13 20:37:13 +00:00
/// <exception cref="ArgumentNullException">message</exception>
2013-02-21 01:33:05 +00:00
public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
2013-02-21 01:33:05 +00:00
}
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(nameof(buffer));
2014-07-20 04:46:29 +00:00
}
cancellationToken.ThrowIfCancellationRequested();
2016-10-07 15:08:13 +00:00
return _socket.SendAsync(buffer, true, cancellationToken);
2013-02-21 01:33:05 +00:00
}
2019-11-01 17:38:54 +00:00
/// <inheritdoc />
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
{
throw new ArgumentNullException(nameof(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
}
2019-11-01 17:38:54 +00:00
/// <inheritdoc />
2013-02-21 01:33:05 +00:00
public void Dispose()
{
Dispose(true);
2019-11-01 17:38:54 +00:00
GC.SuppressFinalize(this);
2013-02-21 01:33:05 +00:00
}
/// <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();
}
}
}
}