BasePeriodicWebSocketListener.cs 8.6 KB

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