BasePeriodicWebSocketListener.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Net.WebSockets;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Model.Net;
  10. using MediaBrowser.Model.Session;
  11. using Microsoft.Extensions.Logging;
  12. namespace MediaBrowser.Controller.Net
  13. {
  14. /// <summary>
  15. /// Starts sending data over a web socket periodically when a message is received, and then stops when a corresponding stop message is received.
  16. /// </summary>
  17. /// <typeparam name="TReturnDataType">The type of the T return data type.</typeparam>
  18. /// <typeparam name="TStateType">The type of the T state type.</typeparam>
  19. public abstract class BasePeriodicWebSocketListener<TReturnDataType, TStateType> : IWebSocketListener, IDisposable
  20. where TStateType : WebSocketListenerState, new()
  21. where TReturnDataType : class
  22. {
  23. /// <summary>
  24. /// The _active connections.
  25. /// </summary>
  26. private readonly List<Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>> _activeConnections =
  27. new List<Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>>();
  28. /// <summary>
  29. /// Gets the type used for the messages sent to the client.
  30. /// </summary>
  31. /// <value>The type.</value>
  32. protected abstract SessionMessageType Type { get; }
  33. /// <summary>
  34. /// Gets the message type received from the client to start sending messages.
  35. /// </summary>
  36. /// <value>The type.</value>
  37. protected abstract SessionMessageType StartType { get; }
  38. /// <summary>
  39. /// Gets the message type received from the client to stop sending messages.
  40. /// </summary>
  41. /// <value>The type.</value>
  42. protected abstract SessionMessageType StopType { get; }
  43. /// <summary>
  44. /// Gets the data to send.
  45. /// </summary>
  46. /// <returns>Task{`1}.</returns>
  47. protected abstract Task<TReturnDataType> GetDataToSend();
  48. /// <summary>
  49. /// The logger.
  50. /// </summary>
  51. protected ILogger<BasePeriodicWebSocketListener<TReturnDataType, TStateType>> Logger;
  52. protected BasePeriodicWebSocketListener(ILogger<BasePeriodicWebSocketListener<TReturnDataType, TStateType>> logger)
  53. {
  54. if (logger == null)
  55. {
  56. throw new ArgumentNullException(nameof(logger));
  57. }
  58. Logger = logger;
  59. }
  60. /// <summary>
  61. /// Processes the message.
  62. /// </summary>
  63. /// <param name="message">The message.</param>
  64. /// <returns>Task.</returns>
  65. public Task ProcessMessageAsync(WebSocketMessageInfo message)
  66. {
  67. if (message == null)
  68. {
  69. throw new ArgumentNullException(nameof(message));
  70. }
  71. if (message.MessageType == StartType)
  72. {
  73. Start(message);
  74. }
  75. if (message.MessageType == StopType)
  76. {
  77. Stop(message);
  78. }
  79. return Task.CompletedTask;
  80. }
  81. /// <inheritdoc />
  82. public Task ProcessWebSocketConnectedAsync(IWebSocketConnection connection) => Task.CompletedTask;
  83. /// <summary>
  84. /// Starts sending messages over a web socket.
  85. /// </summary>
  86. /// <param name="message">The message.</param>
  87. private void Start(WebSocketMessageInfo message)
  88. {
  89. var vals = message.Data.Split(',');
  90. var dueTimeMs = long.Parse(vals[0], CultureInfo.InvariantCulture);
  91. var periodMs = long.Parse(vals[1], CultureInfo.InvariantCulture);
  92. var cancellationTokenSource = new CancellationTokenSource();
  93. Logger.LogDebug("WS {1} begin transmitting to {0}", message.Connection.RemoteEndPoint, GetType().Name);
  94. var state = new TStateType
  95. {
  96. IntervalMs = periodMs,
  97. InitialDelayMs = dueTimeMs
  98. };
  99. lock (_activeConnections)
  100. {
  101. _activeConnections.Add(new Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>(message.Connection, cancellationTokenSource, state));
  102. }
  103. }
  104. protected async Task SendData(bool force)
  105. {
  106. Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>[] tuples;
  107. lock (_activeConnections)
  108. {
  109. tuples = _activeConnections
  110. .Where(c =>
  111. {
  112. if (c.Item1.State == WebSocketState.Open && !c.Item2.IsCancellationRequested)
  113. {
  114. var state = c.Item3;
  115. if (force || (DateTime.UtcNow - state.DateLastSendUtc).TotalMilliseconds >= state.IntervalMs)
  116. {
  117. return true;
  118. }
  119. }
  120. return false;
  121. })
  122. .ToArray();
  123. }
  124. IEnumerable<Task> GetTasks()
  125. {
  126. foreach (var tuple in tuples)
  127. {
  128. yield return SendData(tuple);
  129. }
  130. }
  131. await Task.WhenAll(GetTasks()).ConfigureAwait(false);
  132. }
  133. private async Task SendData(Tuple<IWebSocketConnection, CancellationTokenSource, TStateType> tuple)
  134. {
  135. var connection = tuple.Item1;
  136. try
  137. {
  138. var state = tuple.Item3;
  139. var cancellationToken = tuple.Item2.Token;
  140. var data = await GetDataToSend().ConfigureAwait(false);
  141. if (data != null)
  142. {
  143. await connection.SendAsync(
  144. new WebSocketMessage<TReturnDataType>
  145. {
  146. MessageId = Guid.NewGuid(),
  147. MessageType = Type,
  148. Data = data
  149. },
  150. cancellationToken).ConfigureAwait(false);
  151. state.DateLastSendUtc = DateTime.UtcNow;
  152. }
  153. }
  154. catch (OperationCanceledException)
  155. {
  156. if (tuple.Item2.IsCancellationRequested)
  157. {
  158. DisposeConnection(tuple);
  159. }
  160. }
  161. catch (Exception ex)
  162. {
  163. Logger.LogError(ex, "Error sending web socket message {Name}", Type);
  164. DisposeConnection(tuple);
  165. }
  166. }
  167. /// <summary>
  168. /// Stops sending messages over a web socket.
  169. /// </summary>
  170. /// <param name="message">The message.</param>
  171. private void Stop(WebSocketMessageInfo message)
  172. {
  173. lock (_activeConnections)
  174. {
  175. var connection = _activeConnections.FirstOrDefault(c => c.Item1 == message.Connection);
  176. if (connection != null)
  177. {
  178. DisposeConnection(connection);
  179. }
  180. }
  181. }
  182. /// <summary>
  183. /// Disposes the connection.
  184. /// </summary>
  185. /// <param name="connection">The connection.</param>
  186. private void DisposeConnection(Tuple<IWebSocketConnection, CancellationTokenSource, TStateType> connection)
  187. {
  188. Logger.LogDebug("WS {1} stop transmitting to {0}", connection.Item1.RemoteEndPoint, GetType().Name);
  189. // TODO disposing the connection seems to break websockets in subtle ways, so what is the purpose of this function really...
  190. // connection.Item1.Dispose();
  191. try
  192. {
  193. connection.Item2.Cancel();
  194. connection.Item2.Dispose();
  195. }
  196. catch (ObjectDisposedException)
  197. {
  198. // TODO Investigate and properly fix.
  199. }
  200. lock (_activeConnections)
  201. {
  202. _activeConnections.Remove(connection);
  203. }
  204. }
  205. /// <summary>
  206. /// Releases unmanaged and - optionally - managed resources.
  207. /// </summary>
  208. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  209. protected virtual void Dispose(bool dispose)
  210. {
  211. if (dispose)
  212. {
  213. lock (_activeConnections)
  214. {
  215. foreach (var connection in _activeConnections.ToArray())
  216. {
  217. DisposeConnection(connection);
  218. }
  219. }
  220. }
  221. }
  222. /// <summary>
  223. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  224. /// </summary>
  225. public void Dispose()
  226. {
  227. Dispose(true);
  228. GC.SuppressFinalize(this);
  229. }
  230. }
  231. public class WebSocketListenerState
  232. {
  233. public DateTime DateLastSendUtc { get; set; }
  234. public long InitialDelayMs { get; set; }
  235. public long IntervalMs { get; set; }
  236. }
  237. }