BasePeriodicWebSocketListener.cs 9.0 KB

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