BasePeriodicWebSocketListener.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. protected readonly List<Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType>> ActiveConnections =
  25. new List<Tuple<IWebSocketConnection, CancellationTokenSource, Timer, 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. /// <param name="state">The state.</param>
  35. /// <returns>Task{`1}.</returns>
  36. protected abstract Task<TReturnDataType> GetDataToSend(TStateType state, CancellationToken cancellationToken);
  37. /// <summary>
  38. /// The logger
  39. /// </summary>
  40. protected ILogger Logger;
  41. protected BasePeriodicWebSocketListener(ILogger 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 ProcessMessage(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.FromResult(true);
  69. }
  70. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  71. protected virtual bool SendOnTimer => false;
  72. protected virtual void ParseMessageParams(string[] values)
  73. {
  74. }
  75. /// <summary>
  76. /// Starts sending messages over a web socket
  77. /// </summary>
  78. /// <param name="message">The message.</param>
  79. private void Start(WebSocketMessageInfo message)
  80. {
  81. var vals = message.Data.Split(',');
  82. var dueTimeMs = long.Parse(vals[0], UsCulture);
  83. var periodMs = long.Parse(vals[1], UsCulture);
  84. if (vals.Length > 2)
  85. {
  86. ParseMessageParams(vals.Skip(2).ToArray());
  87. }
  88. var cancellationTokenSource = new CancellationTokenSource();
  89. Logger.LogDebug("{1} Begin transmitting over websocket to {0}", message.Connection.RemoteEndPoint, GetType().Name);
  90. var timer = SendOnTimer ?
  91. new Timer(TimerCallback, message.Connection, Timeout.Infinite, Timeout.Infinite) :
  92. null;
  93. var state = new TStateType
  94. {
  95. IntervalMs = periodMs,
  96. InitialDelayMs = dueTimeMs
  97. };
  98. lock (ActiveConnections)
  99. {
  100. ActiveConnections.Add(new Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType>(message.Connection, cancellationTokenSource, timer, state));
  101. }
  102. if (timer != null)
  103. {
  104. timer.Change(TimeSpan.FromMilliseconds(dueTimeMs), TimeSpan.FromMilliseconds(periodMs));
  105. }
  106. }
  107. /// <summary>
  108. /// Timers the callback.
  109. /// </summary>
  110. /// <param name="state">The state.</param>
  111. private void TimerCallback(object state)
  112. {
  113. var connection = (IWebSocketConnection)state;
  114. Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType> tuple;
  115. lock (ActiveConnections)
  116. {
  117. tuple = ActiveConnections.FirstOrDefault(c => c.Item1 == connection);
  118. }
  119. if (tuple == null)
  120. {
  121. return;
  122. }
  123. if (connection.State != WebSocketState.Open || tuple.Item2.IsCancellationRequested)
  124. {
  125. DisposeConnection(tuple);
  126. return;
  127. }
  128. SendData(tuple);
  129. }
  130. protected void SendData(bool force)
  131. {
  132. Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType>[] tuples;
  133. lock (ActiveConnections)
  134. {
  135. tuples = ActiveConnections
  136. .Where(c =>
  137. {
  138. if (c.Item1.State == WebSocketState.Open && !c.Item2.IsCancellationRequested)
  139. {
  140. var state = c.Item4;
  141. if (force || (DateTime.UtcNow - state.DateLastSendUtc).TotalMilliseconds >= state.IntervalMs)
  142. {
  143. return true;
  144. }
  145. }
  146. return false;
  147. })
  148. .ToArray();
  149. }
  150. foreach (var tuple in tuples)
  151. {
  152. SendData(tuple);
  153. }
  154. }
  155. private async void SendData(Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType> tuple)
  156. {
  157. var connection = tuple.Item1;
  158. try
  159. {
  160. var state = tuple.Item4;
  161. var cancellationToken = tuple.Item2.Token;
  162. var data = await GetDataToSend(state, cancellationToken).ConfigureAwait(false);
  163. if (data != null)
  164. {
  165. await connection.SendAsync(new WebSocketMessage<TReturnDataType>
  166. {
  167. MessageType = Name,
  168. Data = data
  169. }, cancellationToken).ConfigureAwait(false);
  170. state.DateLastSendUtc = DateTime.UtcNow;
  171. }
  172. }
  173. catch (OperationCanceledException)
  174. {
  175. if (tuple.Item2.IsCancellationRequested)
  176. {
  177. DisposeConnection(tuple);
  178. }
  179. }
  180. catch (Exception ex)
  181. {
  182. Logger.LogError(ex, "Error sending web socket message {Name}", Name);
  183. DisposeConnection(tuple);
  184. }
  185. }
  186. /// <summary>
  187. /// Stops sending messages over a web socket
  188. /// </summary>
  189. /// <param name="message">The message.</param>
  190. private void Stop(WebSocketMessageInfo message)
  191. {
  192. lock (ActiveConnections)
  193. {
  194. var connection = ActiveConnections.FirstOrDefault(c => c.Item1 == message.Connection);
  195. if (connection != null)
  196. {
  197. DisposeConnection(connection);
  198. }
  199. }
  200. }
  201. /// <summary>
  202. /// Disposes the connection.
  203. /// </summary>
  204. /// <param name="connection">The connection.</param>
  205. private void DisposeConnection(Tuple<IWebSocketConnection, CancellationTokenSource, Timer, TStateType> connection)
  206. {
  207. Logger.LogDebug("{1} stop transmitting over websocket to {0}", connection.Item1.RemoteEndPoint, GetType().Name);
  208. var timer = connection.Item3;
  209. if (timer != null)
  210. {
  211. try
  212. {
  213. timer.Dispose();
  214. }
  215. catch (ObjectDisposedException)
  216. {
  217. //TODO Investigate and properly fix.
  218. }
  219. }
  220. try
  221. {
  222. connection.Item2.Cancel();
  223. connection.Item2.Dispose();
  224. }
  225. catch (ObjectDisposedException)
  226. {
  227. //TODO Investigate and properly fix.
  228. }
  229. lock (ActiveConnections)
  230. {
  231. ActiveConnections.Remove(connection);
  232. }
  233. }
  234. /// <summary>
  235. /// Releases unmanaged and - optionally - managed resources.
  236. /// </summary>
  237. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  238. protected virtual void Dispose(bool dispose)
  239. {
  240. if (dispose)
  241. {
  242. lock (ActiveConnections)
  243. {
  244. foreach (var connection in ActiveConnections.ToArray())
  245. {
  246. DisposeConnection(connection);
  247. }
  248. }
  249. }
  250. }
  251. /// <summary>
  252. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  253. /// </summary>
  254. public void Dispose()
  255. {
  256. Dispose(true);
  257. }
  258. }
  259. public class WebSocketListenerState
  260. {
  261. public DateTime DateLastSendUtc { get; set; }
  262. public long InitialDelayMs { get; set; }
  263. public long IntervalMs { get; set; }
  264. }
  265. }