BasePeriodicWebSocketListener.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. /// <summary>
  82. /// Starts sending messages over a web socket.
  83. /// </summary>
  84. /// <param name="message">The message.</param>
  85. private void Start(WebSocketMessageInfo message)
  86. {
  87. var vals = message.Data.Split(',');
  88. var dueTimeMs = long.Parse(vals[0], CultureInfo.InvariantCulture);
  89. var periodMs = long.Parse(vals[1], CultureInfo.InvariantCulture);
  90. var cancellationTokenSource = new CancellationTokenSource();
  91. Logger.LogDebug("WS {1} begin transmitting to {0}", message.Connection.RemoteEndPoint, GetType().Name);
  92. var state = new TStateType
  93. {
  94. IntervalMs = periodMs,
  95. InitialDelayMs = dueTimeMs
  96. };
  97. lock (_activeConnections)
  98. {
  99. _activeConnections.Add(new Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>(message.Connection, cancellationTokenSource, state));
  100. }
  101. }
  102. protected async Task SendData(bool force)
  103. {
  104. Tuple<IWebSocketConnection, CancellationTokenSource, TStateType>[] tuples;
  105. lock (_activeConnections)
  106. {
  107. tuples = _activeConnections
  108. .Where(c =>
  109. {
  110. if (c.Item1.State == WebSocketState.Open && !c.Item2.IsCancellationRequested)
  111. {
  112. var state = c.Item3;
  113. if (force || (DateTime.UtcNow - state.DateLastSendUtc).TotalMilliseconds >= state.IntervalMs)
  114. {
  115. return true;
  116. }
  117. }
  118. return false;
  119. })
  120. .ToArray();
  121. }
  122. IEnumerable<Task> GetTasks()
  123. {
  124. foreach (var tuple in tuples)
  125. {
  126. yield return SendData(tuple);
  127. }
  128. }
  129. await Task.WhenAll(GetTasks()).ConfigureAwait(false);
  130. }
  131. private async Task SendData(Tuple<IWebSocketConnection, CancellationTokenSource, TStateType> tuple)
  132. {
  133. var connection = tuple.Item1;
  134. try
  135. {
  136. var state = tuple.Item3;
  137. var cancellationToken = tuple.Item2.Token;
  138. var data = await GetDataToSend().ConfigureAwait(false);
  139. if (data != null)
  140. {
  141. await connection.SendAsync(
  142. new WebSocketMessage<TReturnDataType>
  143. {
  144. MessageId = Guid.NewGuid(),
  145. MessageType = Type,
  146. Data = data
  147. },
  148. cancellationToken).ConfigureAwait(false);
  149. state.DateLastSendUtc = DateTime.UtcNow;
  150. }
  151. }
  152. catch (OperationCanceledException)
  153. {
  154. if (tuple.Item2.IsCancellationRequested)
  155. {
  156. DisposeConnection(tuple);
  157. }
  158. }
  159. catch (Exception ex)
  160. {
  161. Logger.LogError(ex, "Error sending web socket message {Name}", Type);
  162. DisposeConnection(tuple);
  163. }
  164. }
  165. /// <summary>
  166. /// Stops sending messages over a web socket.
  167. /// </summary>
  168. /// <param name="message">The message.</param>
  169. private void Stop(WebSocketMessageInfo message)
  170. {
  171. lock (_activeConnections)
  172. {
  173. var connection = _activeConnections.FirstOrDefault(c => c.Item1 == message.Connection);
  174. if (connection != null)
  175. {
  176. DisposeConnection(connection);
  177. }
  178. }
  179. }
  180. /// <summary>
  181. /// Disposes the connection.
  182. /// </summary>
  183. /// <param name="connection">The connection.</param>
  184. private void DisposeConnection(Tuple<IWebSocketConnection, CancellationTokenSource, TStateType> connection)
  185. {
  186. Logger.LogDebug("WS {1} stop transmitting to {0}", connection.Item1.RemoteEndPoint, GetType().Name);
  187. // TODO disposing the connection seems to break websockets in subtle ways, so what is the purpose of this function really...
  188. // connection.Item1.Dispose();
  189. try
  190. {
  191. connection.Item2.Cancel();
  192. connection.Item2.Dispose();
  193. }
  194. catch (ObjectDisposedException)
  195. {
  196. // TODO Investigate and properly fix.
  197. }
  198. lock (_activeConnections)
  199. {
  200. _activeConnections.Remove(connection);
  201. }
  202. }
  203. /// <summary>
  204. /// Releases unmanaged and - optionally - managed resources.
  205. /// </summary>
  206. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  207. protected virtual void Dispose(bool dispose)
  208. {
  209. if (dispose)
  210. {
  211. lock (_activeConnections)
  212. {
  213. foreach (var connection in _activeConnections.ToArray())
  214. {
  215. DisposeConnection(connection);
  216. }
  217. }
  218. }
  219. }
  220. /// <summary>
  221. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  222. /// </summary>
  223. public void Dispose()
  224. {
  225. Dispose(true);
  226. GC.SuppressFinalize(this);
  227. }
  228. }
  229. public class WebSocketListenerState
  230. {
  231. public DateTime DateLastSendUtc { get; set; }
  232. public long InitialDelayMs { get; set; }
  233. public long IntervalMs { get; set; }
  234. }
  235. }