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

234 lines
7.2 KiB
C#
Raw Normal View History

#nullable enable
using System;
2019-12-17 23:15:02 +01:00
using System.Buffers;
using System.IO.Pipelines;
using System.Net;
using System.Net.WebSockets;
2019-12-17 23:15:02 +01:00
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
2019-12-17 23:15:02 +01:00
using MediaBrowser.Common.Json;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
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>
2019-12-17 23:15:02 +01:00
/// The json serializer options.
2013-02-24 22:53:54 +01:00
/// </summary>
2019-12-17 23:15:02 +01:00
private readonly JsonSerializerOptions _jsonOptions;
/// <summary>
/// The socket.
2013-10-03 03:22:50 +02:00
/// </summary>
2019-12-17 23:15:02 +01:00
private readonly WebSocket _socket;
private bool _disposed = false;
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="logger">The logger.</param>
2013-02-21 02:33:05 +01:00
/// <param name="socket">The socket.</param>
/// <param name="remoteEndPoint">The remote end point.</param>
/// <param name="query">The query.</param>
public WebSocketConnection(
ILogger<WebSocketConnection> logger,
WebSocket socket,
IPAddress? remoteEndPoint,
IQueryCollection query)
2013-02-21 02:33:05 +01:00
{
_logger = logger;
2013-02-21 02:33:05 +01:00
_socket = socket;
RemoteEndPoint = remoteEndPoint;
QueryString = query;
2014-05-17 20:37:40 +02:00
2019-12-17 23:15:02 +01:00
_jsonOptions = JsonDefaults.GetOptions();
LastActivityDate = DateTime.Now;
2014-05-17 20:37:40 +02:00
}
2019-11-01 18:38:54 +01:00
/// <inheritdoc />
public event EventHandler<EventArgs>? Closed;
2019-11-01 18:38:54 +01:00
/// <summary>
/// Gets or sets the remote end point.
2019-11-01 18:38:54 +01:00
/// </summary>
public IPAddress? RemoteEndPoint { get; }
2019-11-01 18:38:54 +01:00
/// <summary>
/// Gets or sets the receive action.
/// </summary>
/// <value>The receive action.</value>
public Func<WebSocketMessageInfo, Task>? OnReceive { get; set; }
2019-11-01 18:38:54 +01:00
/// <summary>
/// Gets the last activity date.
/// </summary>
/// <value>The last activity date.</value>
public DateTime LastActivityDate { get; private set; }
/// <summary>
/// Gets or sets the query string.
/// </summary>
/// <value>The query string.</value>
public IQueryCollection QueryString { get; }
2019-11-01 18:38:54 +01:00
/// <summary>
/// Gets the state.
/// </summary>
/// <value>The state.</value>
public WebSocketState State => _socket.State;
2013-02-21 02:33:05 +01:00
/// <summary>
2019-12-17 23:15:02 +01:00
/// Sends a message asynchronously.
2013-02-21 02:33:05 +01:00
/// </summary>
2019-12-17 23:15:02 +01:00
/// <typeparam name="T"></typeparam>
/// <param name="message">The message.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
/// <exception cref="ArgumentNullException">message</exception>
public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
2013-02-21 02:33:05 +01:00
{
2019-12-17 23:15:02 +01:00
var json = JsonSerializer.SerializeToUtf8Bytes(message, _jsonOptions);
return _socket.SendAsync(json, WebSocketMessageType.Text, true, cancellationToken);
}
/// <inheritdoc />
public async Task ProcessAsync(CancellationToken cancellationToken = default)
{
var pipe = new Pipe();
var writer = pipe.Writer;
ValueWebSocketReceiveResult receiveresult;
do
2015-03-09 01:36:02 +01:00
{
2019-12-17 23:15:02 +01:00
// Allocate at least 512 bytes from the PipeWriter
Memory<byte> memory = writer.GetMemory(512);
receiveresult = await _socket.ReceiveAsync(memory, cancellationToken);
int bytesRead = receiveresult.Count;
if (bytesRead == 0)
{
break;
2019-12-17 23:15:02 +01:00
}
// Tell the PipeWriter how much was read from the Socket
writer.Advance(bytesRead);
// Make the data available to the PipeReader
FlushResult flushResult = await writer.FlushAsync();
if (flushResult.IsCompleted)
{
// The PipeReader stopped reading
break;
}
LastActivityDate = DateTime.UtcNow;
2019-12-17 23:15:02 +01:00
if (receiveresult.EndOfMessage)
{
await ProcessInternal(pipe.Reader).ConfigureAwait(false);
}
} while (_socket.State == WebSocketState.Open && receiveresult.MessageType != WebSocketMessageType.Close);
if (_socket.State == WebSocketState.Open)
2015-03-09 01:36:02 +01:00
{
_logger.LogWarning("Stopped reading from websocket before it was closed");
2015-03-09 01:36:02 +01:00
}
2019-12-17 23:15:02 +01:00
Closed?.Invoke(this, EventArgs.Empty);
_socket.Dispose();
2015-03-09 01:36:02 +01:00
}
2013-02-21 02:33:05 +01:00
2019-12-17 23:15:02 +01:00
private async Task ProcessInternal(PipeReader reader)
{
if (OnReceive == null)
{
return;
}
try
{
2019-12-17 23:15:02 +01:00
var result = await reader.ReadAsync().ConfigureAwait(false);
if (!result.IsCompleted)
{
return;
}
WebSocketMessage<object> stub;
var buffer = result.Buffer;
if (buffer.IsSingleSegment)
{
stub = JsonSerializer.Deserialize<WebSocketMessage<object>>(buffer.FirstSpan, _jsonOptions);
}
else
{
var buf = ArrayPool<byte>.Shared.Rent(Convert.ToInt32(buffer.Length));
try
{
buffer.CopyTo(buf);
stub = JsonSerializer.Deserialize<WebSocketMessage<object>>(buf, _jsonOptions);
}
finally
{
ArrayPool<byte>.Shared.Return(buf);
}
}
var info = new WebSocketMessageInfo
{
MessageType = stub.MessageType,
2019-12-17 23:15:02 +01:00
Data = stub.Data.ToString(),
2014-04-06 19:53:23 +02:00
Connection = this
};
2019-12-17 23:15:02 +01:00
await OnReceive(info).ConfigureAwait(false);
}
2019-12-17 23:15:02 +01:00
catch (JsonException 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
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)
{
2019-12-17 23:15:02 +01:00
if (_disposed)
{
return;
}
2013-02-21 02:33:05 +01:00
if (dispose)
{
_socket.Dispose();
}
2019-12-17 23:15:02 +01:00
_disposed = true;
2013-02-21 02:33:05 +01:00
}
}
}