BasePeriodicWebSocketListener.cs 10.0 KB

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