BasePeriodicWebSocketListener.cs 10 KB

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