2019-01-13 19:25:32 +00:00
|
|
|
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;
|
2019-01-13 19:25:32 +00:00
|
|
|
using System.Threading.Tasks;
|
|
|
|
using MediaBrowser.Model.Net;
|
2018-12-13 13:18:25 +00:00
|
|
|
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>
|
2019-02-05 08:49:46 +00:00
|
|
|
protected readonly List<Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType>> ActiveConnections =
|
|
|
|
new List<Tuple<IWebSocketConnection, CancellationTokenSource, Timer, 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>
|
|
|
|
/// <param name="state">The state.</param>
|
|
|
|
/// <returns>Task{`1}.</returns>
|
|
|
|
protected abstract Task<TReturnDataType> GetDataToSend(TStateType state, CancellationToken cancellationToken);
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// The logger
|
|
|
|
/// </summary>
|
|
|
|
protected ILogger Logger;
|
|
|
|
|
|
|
|
protected BasePeriodicWebSocketListener(ILogger logger)
|
|
|
|
{
|
|
|
|
if (logger == null)
|
|
|
|
{
|
2019-01-06 20:50:43 +00:00
|
|
|
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>
|
|
|
|
public Task ProcessMessage(WebSocketMessageInfo message)
|
|
|
|
{
|
|
|
|
if (message == null)
|
|
|
|
{
|
2019-01-06 20:50:43 +00:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
|
|
|
return Task.FromResult(true);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
|
|
|
|
|
2019-01-13 20:31:14 +00:00
|
|
|
protected virtual bool SendOnTimer => false;
|
2018-12-27 23:27:57 +00:00
|
|
|
|
|
|
|
protected virtual void ParseMessageParams(string[] values)
|
|
|
|
{
|
2019-01-07 23:27:46 +00:00
|
|
|
|
2018-12-27 23:27:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <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);
|
|
|
|
|
|
|
|
if (vals.Length > 2)
|
|
|
|
{
|
|
|
|
ParseMessageParams(vals.Skip(2).ToArray());
|
|
|
|
}
|
|
|
|
|
|
|
|
var cancellationTokenSource = new CancellationTokenSource();
|
|
|
|
|
2018-12-13 13:18:25 +00:00
|
|
|
Logger.LogDebug("{1} Begin transmitting over websocket to {0}", message.Connection.RemoteEndPoint, GetType().Name);
|
2018-12-27 23:27:57 +00:00
|
|
|
|
|
|
|
var timer = SendOnTimer ?
|
2019-02-05 08:49:46 +00:00
|
|
|
new Timer(TimerCallback, message.Connection, Timeout.Infinite, Timeout.Infinite) :
|
2018-12-27 23:27:57 +00:00
|
|
|
null;
|
|
|
|
|
|
|
|
var state = new TStateType
|
|
|
|
{
|
|
|
|
IntervalMs = periodMs,
|
|
|
|
InitialDelayMs = dueTimeMs
|
|
|
|
};
|
|
|
|
|
|
|
|
lock (ActiveConnections)
|
|
|
|
{
|
2019-02-05 08:49:46 +00:00
|
|
|
ActiveConnections.Add(new Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType>(message.Connection, cancellationTokenSource, timer, state));
|
2018-12-27 23:27:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (timer != null)
|
|
|
|
{
|
|
|
|
timer.Change(TimeSpan.FromMilliseconds(dueTimeMs), TimeSpan.FromMilliseconds(periodMs));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Timers the callback.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="state">The state.</param>
|
|
|
|
private void TimerCallback(object state)
|
|
|
|
{
|
|
|
|
var connection = (IWebSocketConnection)state;
|
|
|
|
|
2019-02-05 08:49:46 +00:00
|
|
|
Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType> tuple;
|
2018-12-27 23:27:57 +00:00
|
|
|
|
|
|
|
lock (ActiveConnections)
|
|
|
|
{
|
|
|
|
tuple = ActiveConnections.FirstOrDefault(c => c.Item1 == connection);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (tuple == null)
|
|
|
|
{
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (connection.State != WebSocketState.Open || tuple.Item2.IsCancellationRequested)
|
|
|
|
{
|
|
|
|
DisposeConnection(tuple);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
SendData(tuple);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected void SendData(bool force)
|
|
|
|
{
|
2019-02-05 08:49:46 +00:00
|
|
|
Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType>[] tuples;
|
2018-12-27 23:27:57 +00:00
|
|
|
|
|
|
|
lock (ActiveConnections)
|
|
|
|
{
|
|
|
|
tuples = ActiveConnections
|
|
|
|
.Where(c =>
|
|
|
|
{
|
|
|
|
if (c.Item1.State == WebSocketState.Open && !c.Item2.IsCancellationRequested)
|
|
|
|
{
|
|
|
|
var state = c.Item4;
|
|
|
|
|
|
|
|
if (force || (DateTime.UtcNow - state.DateLastSendUtc).TotalMilliseconds >= state.IntervalMs)
|
|
|
|
{
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
})
|
|
|
|
.ToArray();
|
|
|
|
}
|
|
|
|
|
|
|
|
foreach (var tuple in tuples)
|
|
|
|
{
|
|
|
|
SendData(tuple);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-05 08:49:46 +00:00
|
|
|
private async void SendData(Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType> tuple)
|
2018-12-27 23:27:57 +00:00
|
|
|
{
|
|
|
|
var connection = tuple.Item1;
|
|
|
|
|
|
|
|
try
|
|
|
|
{
|
|
|
|
var state = tuple.Item4;
|
|
|
|
|
|
|
|
var cancellationToken = tuple.Item2.Token;
|
|
|
|
|
|
|
|
var data = await GetDataToSend(state, cancellationToken).ConfigureAwait(false);
|
|
|
|
|
|
|
|
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)
|
|
|
|
{
|
|
|
|
var connection = ActiveConnections.FirstOrDefault(c => c.Item1 == message.Connection);
|
|
|
|
|
|
|
|
if (connection != null)
|
|
|
|
{
|
|
|
|
DisposeConnection(connection);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Disposes the connection.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="connection">The connection.</param>
|
2019-02-05 08:49:46 +00:00
|
|
|
private void DisposeConnection(Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType> connection)
|
2018-12-27 23:27:57 +00:00
|
|
|
{
|
2018-12-13 13:18:25 +00:00
|
|
|
Logger.LogDebug("{1} stop transmitting over websocket to {0}", connection.Item1.RemoteEndPoint, GetType().Name);
|
2018-12-27 23:27:57 +00:00
|
|
|
|
|
|
|
var timer = connection.Item3;
|
|
|
|
|
|
|
|
if (timer != null)
|
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
|
|
|
timer.Dispose();
|
|
|
|
}
|
|
|
|
catch (ObjectDisposedException)
|
|
|
|
{
|
2019-01-06 20:50:43 +00:00
|
|
|
//TODO Investigate and properly fix.
|
2018-12-27 23:27:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
try
|
|
|
|
{
|
|
|
|
connection.Item2.Cancel();
|
|
|
|
connection.Item2.Dispose();
|
|
|
|
}
|
|
|
|
catch (ObjectDisposedException)
|
|
|
|
{
|
2019-01-06 20:50:43 +00:00
|
|
|
//TODO Investigate and properly fix.
|
2018-12-27 23:27:57 +00:00
|
|
|
}
|
|
|
|
|
2019-01-06 20:50:43 +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)
|
|
|
|
{
|
|
|
|
foreach (var connection in ActiveConnections.ToArray())
|
|
|
|
{
|
|
|
|
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; }
|
|
|
|
}
|
|
|
|
}
|