BasePeriodicWebSocketListener.cs 9.0 KB

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