BasePeriodicWebSocketListener.cs 10.0 KB

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