BasePeriodicWebSocketListener.cs 8.5 KB

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