2019-02-27 22:22:55 +00:00
|
|
|
using System;
|
2019-03-01 13:08:51 +00:00
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.Linq;
|
2019-02-27 22:22:55 +00:00
|
|
|
using System.Net.WebSockets;
|
2019-03-01 13:08:51 +00:00
|
|
|
using System.Text;
|
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using MediaBrowser.Model.Net;
|
|
|
|
using MediaBrowser.Model.Serialization;
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
using UtfUnknown;
|
2019-02-27 22:22:55 +00:00
|
|
|
|
|
|
|
namespace Emby.Server.Implementations.WebSockets
|
|
|
|
{
|
|
|
|
public class WebSocketManager
|
|
|
|
{
|
2019-03-01 13:08:51 +00:00
|
|
|
private readonly IWebSocketHandler[] _webSocketHandlers;
|
|
|
|
private readonly IJsonSerializer _jsonSerializer;
|
|
|
|
private readonly ILogger<WebSocketManager> _logger;
|
|
|
|
private const int BufferSize = 4096;
|
2019-02-27 22:22:55 +00:00
|
|
|
|
2019-03-01 13:08:51 +00:00
|
|
|
public WebSocketManager(IWebSocketHandler[] webSocketHandlers, IJsonSerializer jsonSerializer, ILogger<WebSocketManager> logger)
|
2019-02-27 22:22:55 +00:00
|
|
|
{
|
2019-03-01 13:08:51 +00:00
|
|
|
_webSocketHandlers = webSocketHandlers;
|
|
|
|
_jsonSerializer = jsonSerializer;
|
|
|
|
_logger = logger;
|
2019-02-27 22:22:55 +00:00
|
|
|
}
|
|
|
|
|
2019-03-01 13:08:51 +00:00
|
|
|
public async Task OnWebSocketConnected(WebSocket webSocket)
|
2019-02-27 22:22:55 +00:00
|
|
|
{
|
2019-03-01 13:08:51 +00:00
|
|
|
var taskCompletionSource = new TaskCompletionSource<bool>();
|
|
|
|
var cancellationToken = new CancellationTokenSource().Token;
|
|
|
|
WebSocketReceiveResult result;
|
|
|
|
var message = new List<byte>();
|
|
|
|
|
2019-03-03 07:29:23 +00:00
|
|
|
// Keep listening for incoming messages, otherwise the socket closes automatically
|
2019-03-01 13:08:51 +00:00
|
|
|
do
|
|
|
|
{
|
|
|
|
var buffer = WebSocket.CreateServerBuffer(BufferSize);
|
2019-10-25 10:47:20 +00:00
|
|
|
result = await webSocket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false);
|
2019-03-01 13:08:51 +00:00
|
|
|
message.AddRange(buffer.Array.Take(result.Count));
|
|
|
|
|
|
|
|
if (result.EndOfMessage)
|
|
|
|
{
|
2019-10-25 10:47:20 +00:00
|
|
|
await ProcessMessage(message.ToArray(), taskCompletionSource).ConfigureAwait(false);
|
2019-03-01 13:08:51 +00:00
|
|
|
message.Clear();
|
|
|
|
}
|
|
|
|
} while (!taskCompletionSource.Task.IsCompleted &&
|
|
|
|
webSocket.State == WebSocketState.Open &&
|
|
|
|
result.MessageType != WebSocketMessageType.Close);
|
|
|
|
|
|
|
|
if (webSocket.State == WebSocketState.Open)
|
|
|
|
{
|
2019-10-25 10:47:20 +00:00
|
|
|
await webSocket.CloseAsync(
|
|
|
|
result.CloseStatus ?? WebSocketCloseStatus.NormalClosure,
|
|
|
|
result.CloseStatusDescription,
|
|
|
|
cancellationToken).ConfigureAwait(false);
|
2019-03-01 13:08:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-03 07:29:23 +00:00
|
|
|
private async Task ProcessMessage(byte[] messageBytes, TaskCompletionSource<bool> taskCompletionSource)
|
2019-03-01 13:08:51 +00:00
|
|
|
{
|
|
|
|
var charset = CharsetDetector.DetectFromBytes(messageBytes).Detected?.EncodingName;
|
|
|
|
var message = string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase)
|
|
|
|
? Encoding.UTF8.GetString(messageBytes, 0, messageBytes.Length)
|
|
|
|
: Encoding.ASCII.GetString(messageBytes, 0, messageBytes.Length);
|
|
|
|
|
2019-03-06 18:14:03 +00:00
|
|
|
// All messages are expected to be valid JSON objects
|
2019-03-01 13:08:51 +00:00
|
|
|
if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
|
|
|
|
{
|
|
|
|
_logger.LogDebug("Received web socket message that is not a json structure: {Message}", message);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
try
|
|
|
|
{
|
|
|
|
var info = _jsonSerializer.DeserializeFromString<WebSocketMessage<object>>(message);
|
|
|
|
|
|
|
|
_logger.LogDebug("Websocket message received: {0}", info.MessageType);
|
|
|
|
|
|
|
|
var tasks = _webSocketHandlers.Select(handler => Task.Run(() =>
|
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
2019-03-03 07:29:23 +00:00
|
|
|
handler.ProcessMessage(info, taskCompletionSource).ConfigureAwait(false);
|
2019-03-01 13:08:51 +00:00
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
2019-03-03 07:29:23 +00:00
|
|
|
_logger.LogError(ex, "{HandlerType} failed processing WebSocket message {MessageType}",
|
|
|
|
handler.GetType().Name, info.MessageType ?? string.Empty);
|
2019-03-01 13:08:51 +00:00
|
|
|
}
|
|
|
|
}));
|
|
|
|
|
|
|
|
await Task.WhenAll(tasks);
|
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
|
|
|
_logger.LogError(ex, "Error processing web socket message");
|
|
|
|
}
|
2019-02-27 22:22:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|