BasePeriodicWebSocketListener.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 Logger;
  40. protected BasePeriodicWebSocketListener(ILogger 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 void 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. foreach (var tuple in tuples)
  111. {
  112. SendData(tuple);
  113. }
  114. }
  115. private async void SendData(Tuple<IWebSocketConnection, CancellationTokenSource, TStateType> tuple)
  116. {
  117. var connection = tuple.Item1;
  118. try
  119. {
  120. var state = tuple.Item3;
  121. var cancellationToken = tuple.Item2.Token;
  122. var data = await GetDataToSend().ConfigureAwait(false);
  123. if (data != null)
  124. {
  125. await connection.SendAsync(new WebSocketMessage<TReturnDataType>
  126. {
  127. MessageType = Name,
  128. Data = data
  129. }, cancellationToken).ConfigureAwait(false);
  130. state.DateLastSendUtc = DateTime.UtcNow;
  131. }
  132. }
  133. catch (OperationCanceledException)
  134. {
  135. if (tuple.Item2.IsCancellationRequested)
  136. {
  137. DisposeConnection(tuple);
  138. }
  139. }
  140. catch (Exception ex)
  141. {
  142. Logger.LogError(ex, "Error sending web socket message {Name}", Name);
  143. DisposeConnection(tuple);
  144. }
  145. }
  146. /// <summary>
  147. /// Stops sending messages over a web socket
  148. /// </summary>
  149. /// <param name="message">The message.</param>
  150. private void Stop(WebSocketMessageInfo message)
  151. {
  152. lock (_activeConnections)
  153. {
  154. var connection = _activeConnections.FirstOrDefault(c => c.Item1 == message.Connection);
  155. if (connection != null)
  156. {
  157. DisposeConnection(connection);
  158. }
  159. }
  160. }
  161. /// <summary>
  162. /// Disposes the connection.
  163. /// </summary>
  164. /// <param name="connection">The connection.</param>
  165. private void DisposeConnection(Tuple<IWebSocketConnection, CancellationTokenSource, TStateType> connection)
  166. {
  167. Logger.LogDebug("WS {1} stop transmitting to {0}", connection.Item1.RemoteEndPoint, GetType().Name);
  168. // TODO disposing the connection seems to break websockets in subtle ways, so what is the purpose of this function really...
  169. // connection.Item1.Dispose();
  170. try
  171. {
  172. connection.Item2.Cancel();
  173. connection.Item2.Dispose();
  174. }
  175. catch (ObjectDisposedException)
  176. {
  177. //TODO Investigate and properly fix.
  178. }
  179. lock (_activeConnections)
  180. {
  181. _activeConnections.Remove(connection);
  182. }
  183. }
  184. /// <summary>
  185. /// Releases unmanaged and - optionally - managed resources.
  186. /// </summary>
  187. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  188. protected virtual void Dispose(bool dispose)
  189. {
  190. if (dispose)
  191. {
  192. lock (_activeConnections)
  193. {
  194. foreach (var connection in _activeConnections.ToArray())
  195. {
  196. DisposeConnection(connection);
  197. }
  198. }
  199. }
  200. }
  201. /// <summary>
  202. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  203. /// </summary>
  204. public void Dispose()
  205. {
  206. Dispose(true);
  207. GC.SuppressFinalize(this);
  208. }
  209. }
  210. public class WebSocketListenerState
  211. {
  212. public DateTime DateLastSendUtc { get; set; }
  213. public long InitialDelayMs { get; set; }
  214. public long IntervalMs { get; set; }
  215. }
  216. }