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

270 lines
8.3 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 22:53:54 +01:00
using MediaBrowser.Model.Serialization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using UtfUnknown;
2013-02-21 02:33:05 +01:00
2018-09-12 19:26:21 +02:00
namespace Emby.Server.Implementations.HttpServer
2013-02-21 02:33:05 +01:00
{
/// <summary>
2019-11-01 18:38:54 +01:00
/// Class WebSocketConnection.
2013-02-21 02:33:05 +01:00
/// </summary>
public class WebSocketConnection : IWebSocketConnection
2013-02-21 02:33:05 +01:00
{
/// <summary>
2019-11-01 18:38:54 +01:00
/// The logger.
2013-02-21 02:33:05 +01:00
/// </summary>
2013-02-21 22:06:23 +01:00
private readonly ILogger _logger;
2013-02-21 02:33:05 +01:00
2013-02-24 22:53:54 +01:00
/// <summary>
/// The json serializer.
2013-02-24 22:53:54 +01:00
/// </summary>
private readonly IJsonSerializer _jsonSerializer;
/// <summary>
/// The socket.
2013-10-03 03:22:50 +02:00
/// </summary>
2019-11-01 18:38:54 +01:00
private readonly IWebSocket _socket;
2016-10-06 20:55:01 +02:00
2013-02-21 02:33:05 +01: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 22:53:54 +01:00
/// <param name="jsonSerializer">The json serializer.</param>
/// <param name="logger">The logger.</param>
2019-01-13 21:37:13 +01:00
/// <exception cref="ArgumentNullException">socket</exception>
public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger)
2013-02-21 02:33:05 +01:00
{
if (socket == null)
{
throw new ArgumentNullException(nameof(socket));
2013-02-21 02:33:05 +01:00
}
2019-11-01 18:38:54 +01:00
if (string.IsNullOrEmpty(remoteEndPoint))
2013-02-21 02:33:05 +01:00
{
throw new ArgumentNullException(nameof(remoteEndPoint));
2013-02-21 02:33:05 +01:00
}
2019-11-01 18:38:54 +01:00
2013-02-24 22:53:54 +01:00
if (jsonSerializer == null)
{
throw new ArgumentNullException(nameof(jsonSerializer));
2013-02-24 22:53:54 +01:00
}
2019-11-01 18:38:54 +01:00
2013-02-21 22:06:23 +01:00
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
2013-02-21 22:06:23 +01:00
}
2013-02-21 02:33:05 +01:00
2013-10-03 03:22:50 +02:00
Id = Guid.NewGuid();
2013-02-24 22:53:54 +01:00
_jsonSerializer = jsonSerializer;
2013-02-21 02:33:05 +01:00
_socket = socket;
_socket.OnReceiveBytes = OnReceiveInternal;
2018-09-12 19:26:21 +02:00
2013-02-21 02:33:05 +01:00
RemoteEndPoint = remoteEndPoint;
2013-02-21 22:06:23 +01:00
_logger = logger;
2014-05-17 20:37:40 +02:00
2019-11-01 18:38:54 +01:00
socket.Closed += OnSocketClosed;
2014-05-17 20:37:40 +02:00
}
2019-11-01 18:38:54 +01:00
/// <inheritdoc />
public event EventHandler<EventArgs> Closed;
/// <summary>
/// Gets or sets the remote end point.
2019-11-01 18:38:54 +01: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; }
2020-04-17 13:47:00 +02:00
/// <inheritdoc />
public DateTime LastKeepAliveDate { get; set; }
2019-11-01 18:38:54 +01:00
/// <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 20:37:40 +02:00
{
Closed?.Invoke(this, EventArgs.Empty);
2013-02-21 02:33:05 +01:00
}
/// <summary>
/// Called when [receive].
/// </summary>
2013-02-24 22:53:54 +01:00
/// <param name="bytes">The bytes.</param>
private void OnReceiveInternal(byte[] bytes)
2013-02-21 02:33:05 +01:00
{
2013-05-26 02:53:51 +02:00
LastActivityDate = DateTime.UtcNow;
if (OnReceive == null)
{
return;
}
var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName;
2015-03-09 01:36:02 +01:00
if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
{
2016-11-03 23:53:02 +01:00
OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
2015-03-09 01:36:02 +01:00
}
else
{
OnReceiveInternal(Encoding.ASCII.GetString(bytes, 0, bytes.Length));
2015-03-09 01:36:02 +01:00
}
}
2013-02-21 02:33:05 +01:00
private void OnReceiveInternal(string message)
{
LastActivityDate = DateTime.UtcNow;
if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
{
2015-06-07 23:21:30 +02:00
// This info is useful sometimes but also clogs up the log
2018-12-20 13:11:26 +01:00
_logger.LogDebug("Received web socket message that is not a json structure: {message}", message);
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 19:53:23 +02:00
Connection = this
};
2020-04-17 13:47:00 +02:00
if (info.MessageType.Equals("KeepAlive", StringComparison.Ordinal))
{
SendKeepAliveResponse();
}
2020-04-21 23:37:37 +02:00
else
2020-04-17 13:47:00 +02:00
{
2020-04-21 23:37:37 +02:00
OnReceive?.Invoke(info);
2020-04-17 13:47:00 +02:00
}
}
catch (Exception ex)
{
2018-12-20 13:11:26 +01:00
_logger.LogError(ex, "Error processing web socket message");
}
}
2016-10-07 17:08:13 +02:00
2013-02-21 02:33:05 +01: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 21:37:13 +01:00
/// <exception cref="ArgumentNullException">message</exception>
2013-02-21 02:33:05 +01:00
public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
2013-02-21 02:33:05 +01:00
}
2013-02-24 22:53:54 +01:00
2014-07-20 06:46:29 +02:00
var json = _jsonSerializer.SerializeToString(message);
2013-02-21 02:33:05 +01:00
2014-07-20 06:46:29 +02:00
return SendAsync(json, cancellationToken);
2013-02-21 02:33:05 +01: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 17:08:13 +02:00
public Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
2013-02-21 02:33:05 +01:00
{
2014-07-20 06:46:29 +02:00
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
2014-07-20 06:46:29 +02:00
}
cancellationToken.ThrowIfCancellationRequested();
2016-10-07 17:08:13 +02:00
return _socket.SendAsync(buffer, true, cancellationToken);
2013-02-21 02:33:05 +01:00
}
2019-11-01 18:38:54 +01:00
/// <inheritdoc />
2016-10-07 17:08:13 +02:00
public Task SendAsync(string text, CancellationToken cancellationToken)
2013-02-21 02:33:05 +01:00
{
2018-09-12 19:26:21 +02:00
if (string.IsNullOrEmpty(text))
2013-02-21 02:33:05 +01:00
{
throw new ArgumentNullException(nameof(text));
2013-02-21 02:33:05 +01:00
}
cancellationToken.ThrowIfCancellationRequested();
2016-10-07 17:08:13 +02:00
return _socket.SendAsync(text, true, cancellationToken);
2013-02-21 02:33:05 +01:00
}
2020-05-04 19:46:02 +02:00
private void SendKeepAliveResponse()
2020-04-17 13:47:00 +02:00
{
LastKeepAliveDate = DateTime.UtcNow;
2020-05-04 19:46:02 +02:00
SendAsync(new WebSocketMessage<string>
2020-04-17 13:47:00 +02:00
{
MessageType = "KeepAlive"
}, CancellationToken.None);
}
2019-11-01 18:38:54 +01:00
/// <inheritdoc />
2013-02-21 02:33:05 +01:00
public void Dispose()
{
Dispose(true);
2019-11-01 18:38:54 +01:00
GC.SuppressFinalize(this);
2013-02-21 02:33:05 +01: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();
}
}
}
}