BasePeriodicWebSocketListener.cs 9.9 KB

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