using MediaBrowser.Common.Logging;
using MediaBrowser.Common.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Common.Kernel
{
///
/// Starts sending data over a web socket periodically when a message is received, and then stops when a corresponding stop message is received
///
/// The type of the T kernel type.
/// The type of the T return data type.
/// The type of the T state type.
public abstract class BasePeriodicWebSocketListener : BaseWebSocketListener
where TKernelType : IKernel
where TStateType : class, new()
{
///
/// The _active connections
///
protected readonly List> ActiveConnections =
new List>();
///
/// Gets the name.
///
/// The name.
protected abstract string Name { get; }
///
/// Gets the data to send.
///
/// The state.
/// Task{`1}.
protected abstract Task GetDataToSend(TStateType state);
///
/// Processes the message internal.
///
/// The message.
/// Task.
protected override Task ProcessMessageInternal(WebSocketMessageInfo message)
{
if (message.MessageType.Equals(Name + "Start", StringComparison.OrdinalIgnoreCase))
{
Start(message);
}
if (message.MessageType.Equals(Name + "Stop", StringComparison.OrdinalIgnoreCase))
{
Stop(message);
}
return NullTaskResult;
}
///
/// Starts sending messages over a web socket
///
/// The message.
private void Start(WebSocketMessageInfo message)
{
var vals = message.Data.Split(',');
var dueTimeMs = long.Parse(vals[0]);
var periodMs = long.Parse(vals[1]);
var cancellationTokenSource = new CancellationTokenSource();
Logger.LogInfo("{1} Begin transmitting over websocket to {0}", message.Connection.RemoteEndPoint, GetType().Name);
var timer = new Timer(TimerCallback, message.Connection, Timeout.Infinite, Timeout.Infinite);
var state = new TStateType();
var semaphore = new SemaphoreSlim(1, 1);
lock (ActiveConnections)
{
ActiveConnections.Add(new Tuple(message.Connection, cancellationTokenSource, timer, state, semaphore));
}
timer.Change(TimeSpan.FromMilliseconds(dueTimeMs), TimeSpan.FromMilliseconds(periodMs));
}
///
/// Timers the callback.
///
/// The state.
private async void TimerCallback(object state)
{
var connection = (WebSocketConnection)state;
Tuple tuple;
lock (ActiveConnections)
{
tuple = ActiveConnections.FirstOrDefault(c => c.Item1 == connection);
}
if (tuple == null)
{
return;
}
if (connection.State != WebSocketState.Open || tuple.Item2.IsCancellationRequested)
{
DisposeConnection(tuple);
return;
}
try
{
await tuple.Item5.WaitAsync(tuple.Item2.Token).ConfigureAwait(false);
var data = await GetDataToSend(tuple.Item4).ConfigureAwait(false);
await connection.SendAsync(new WebSocketMessage
{
MessageType = Name,
Data = data
}, tuple.Item2.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
if (tuple.Item2.IsCancellationRequested)
{
DisposeConnection(tuple);
}
}
catch (Exception ex)
{
Logger.LogException("Error sending web socket message {0}", ex, Name);
DisposeConnection(tuple);
}
finally
{
tuple.Item5.Release();
}
}
///
/// Stops sending messages over a web socket
///
/// The message.
private void Stop(WebSocketMessageInfo message)
{
lock (ActiveConnections)
{
var connection = ActiveConnections.FirstOrDefault(c => c.Item1 == message.Connection);
if (connection != null)
{
DisposeConnection(connection);
}
}
}
///
/// Disposes the connection.
///
/// The connection.
private void DisposeConnection(Tuple connection)
{
Logger.LogInfo("{1} stop transmitting over websocket to {0}", connection.Item1.RemoteEndPoint, GetType().Name);
try
{
connection.Item3.Dispose();
}
catch (ObjectDisposedException)
{
}
try
{
connection.Item2.Cancel();
connection.Item2.Dispose();
}
catch (ObjectDisposedException)
{
}
try
{
connection.Item5.Dispose();
}
catch (ObjectDisposedException)
{
}
ActiveConnections.Remove(connection);
}
///
/// Releases unmanaged and - optionally - managed resources.
///
/// true to release both managed and unmanaged resources; false to release only unmanaged resources.
protected override void Dispose(bool dispose)
{
if (dispose)
{
lock (ActiveConnections)
{
foreach (var connection in ActiveConnections.ToList())
{
DisposeConnection(connection);
}
}
}
base.Dispose(dispose);
}
}
}