jellyfin-server/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs

255 lines
8.2 KiB
C#
Raw Normal View History

using System;
2018-12-27 23:27:57 +00:00
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Net;
using Microsoft.Extensions.Logging;
2018-12-27 23:27:57 +00:00
namespace MediaBrowser.Controller.Net
{
/// <summary>
/// Starts sending data over a web socket periodically when a message is received, and then stops when a corresponding stop message is received
/// </summary>
/// <typeparam name="TReturnDataType">The type of the T return data type.</typeparam>
/// <typeparam name="TStateType">The type of the T state type.</typeparam>
public abstract class BasePeriodicWebSocketListener<TReturnDataType, TStateType> : IWebSocketListener, IDisposable
where TStateType : WebSocketListenerState, new()
where TReturnDataType : class
{
/// <summary>
/// The _active connections
/// </summary>
private readonly List<Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>> _activeConnections =
2019-02-27 21:09:22 +00:00
new List<Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>>();
2018-12-27 23:27:57 +00:00
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
protected abstract string Name { get; }
/// <summary>
/// Gets the data to send.
/// </summary>
/// <returns>Task{`1}.</returns>
2019-02-27 21:09:22 +00:00
protected abstract Task<TReturnDataType> GetDataToSend();
2018-12-27 23:27:57 +00:00
/// <summary>
/// The logger
/// </summary>
protected ILogger Logger;
protected BasePeriodicWebSocketListener(ILogger logger)
{
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
2018-12-27 23:27:57 +00:00
}
Logger = logger;
}
/// <summary>
/// Processes the message.
/// </summary>
/// <param name="message">The message.</param>
/// <returns>Task.</returns>
2019-02-24 02:16:19 +00:00
public Task ProcessMessageAsync(WebSocketMessageInfo message)
2018-12-27 23:27:57 +00:00
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
2018-12-27 23:27:57 +00:00
}
if (string.Equals(message.MessageType, Name + "Start", StringComparison.OrdinalIgnoreCase))
{
Start(message);
}
if (string.Equals(message.MessageType, Name + "Stop", StringComparison.OrdinalIgnoreCase))
{
Stop(message);
}
2019-02-24 02:16:19 +00:00
return Task.CompletedTask;
2018-12-27 23:27:57 +00:00
}
protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
/// <summary>
/// Starts sending messages over a web socket
/// </summary>
/// <param name="message">The message.</param>
private void Start(WebSocketMessageInfo message)
{
var vals = message.Data.Split(',');
var dueTimeMs = long.Parse(vals[0], UsCulture);
var periodMs = long.Parse(vals[1], UsCulture);
var cancellationTokenSource = new CancellationTokenSource();
Logger.LogDebug("{1} Begin transmitting over websocket to {0}", message.Connection.RemoteEndPoint, GetType().Name);
2018-12-27 23:27:57 +00:00
var state = new TStateType
{
IntervalMs = periodMs,
InitialDelayMs = dueTimeMs
};
lock (_activeConnections)
2018-12-27 23:27:57 +00:00
{
_activeConnections.Add(new Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>(message.Connection, cancellationTokenSource, state));
2018-12-27 23:27:57 +00:00
}
}
protected void SendData(bool force)
{
2019-02-27 21:09:22 +00:00
Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>[] tuples;
2018-12-27 23:27:57 +00:00
lock (_activeConnections)
2018-12-27 23:27:57 +00:00
{
tuples = _activeConnections
2018-12-27 23:27:57 +00:00
.Where(c =>
{
if (c.Item1.State == WebSocketState.Open && !c.Item2.IsCancellationRequested)
{
2019-02-27 21:09:22 +00:00
var state = c.Item3;
2018-12-27 23:27:57 +00:00
if (force || (DateTime.UtcNow - state.DateLastSendUtc).TotalMilliseconds >= state.IntervalMs)
{
return true;
}
}
return false;
})
.ToArray();
}
foreach (var tuple in tuples)
{
SendData(tuple);
}
}
2019-02-27 21:09:22 +00:00
private async void SendData(Tuple<IWebSocketConnection, CancellationTokenSource, TStateType> tuple)
2018-12-27 23:27:57 +00:00
{
var connection = tuple.Item1;
try
{
2019-02-27 21:09:22 +00:00
var state = tuple.Item3;
2018-12-27 23:27:57 +00:00
var cancellationToken = tuple.Item2.Token;
2019-02-27 21:09:22 +00:00
var data = await GetDataToSend().ConfigureAwait(false);
2018-12-27 23:27:57 +00:00
if (data != null)
{
await connection.SendAsync(new WebSocketMessage<TReturnDataType>
{
MessageType = Name,
Data = data
}, cancellationToken).ConfigureAwait(false);
state.DateLastSendUtc = DateTime.UtcNow;
}
}
catch (OperationCanceledException)
{
if (tuple.Item2.IsCancellationRequested)
{
DisposeConnection(tuple);
}
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
Logger.LogError(ex, "Error sending web socket message {Name}", Name);
2018-12-27 23:27:57 +00:00
DisposeConnection(tuple);
}
}
/// <summary>
/// Stops sending messages over a web socket
/// </summary>
/// <param name="message">The message.</param>
private void Stop(WebSocketMessageInfo message)
{
lock (_activeConnections)
2018-12-27 23:27:57 +00:00
{
var connection = _activeConnections.FirstOrDefault(c => c.Item1 == message.Connection);
2018-12-27 23:27:57 +00:00
if (connection != null)
{
DisposeConnection(connection);
}
}
}
/// <summary>
/// Disposes the connection.
/// </summary>
/// <param name="connection">The connection.</param>
2019-02-27 21:09:22 +00:00
private void DisposeConnection(Tuple<IWebSocketConnection, CancellationTokenSource, TStateType> connection)
2018-12-27 23:27:57 +00:00
{
Logger.LogDebug("{1} stop transmitting over websocket to {0}", connection.Item1.RemoteEndPoint, GetType().Name);
2018-12-27 23:27:57 +00:00
2019-03-05 06:41:41 +00:00
// TODO disposing the connection seems to break websockets in subtle ways, so what is the purpose of this function really...
// connection.Item1.Dispose();
2018-12-27 23:27:57 +00:00
try
{
connection.Item2.Cancel();
connection.Item2.Dispose();
}
catch (ObjectDisposedException)
{
//TODO Investigate and properly fix.
2018-12-27 23:27:57 +00:00
}
lock (_activeConnections)
{
_activeConnections.Remove(connection);
}
2018-12-27 23:27:57 +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)
{
lock (_activeConnections)
2018-12-27 23:27:57 +00:00
{
foreach (var connection in _activeConnections.ToArray())
2018-12-27 23:27:57 +00:00
{
DisposeConnection(connection);
}
}
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
}
}
public class WebSocketListenerState
{
public DateTime DateLastSendUtc { get; set; }
public long InitialDelayMs { get; set; }
public long IntervalMs { get; set; }
}
}