WebSocketConnection.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. using System.Text;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Controller.Net;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Net;
  6. using MediaBrowser.Model.Serialization;
  7. using System;
  8. using System.Collections.Specialized;
  9. using System.IO;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using MediaBrowser.Common.IO;
  13. using UniversalDetector;
  14. namespace MediaBrowser.Server.Implementations.ServerManager
  15. {
  16. /// <summary>
  17. /// Class WebSocketConnection
  18. /// </summary>
  19. public class WebSocketConnection : IWebSocketConnection
  20. {
  21. public event EventHandler<EventArgs> Closed;
  22. /// <summary>
  23. /// The _socket
  24. /// </summary>
  25. private readonly IWebSocket _socket;
  26. /// <summary>
  27. /// The _remote end point
  28. /// </summary>
  29. public string RemoteEndPoint { get; private set; }
  30. /// <summary>
  31. /// The _cancellation token source
  32. /// </summary>
  33. private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
  34. /// <summary>
  35. /// The _send semaphore
  36. /// </summary>
  37. private readonly SemaphoreSlim _sendSemaphore = new SemaphoreSlim(1, 1);
  38. /// <summary>
  39. /// The logger
  40. /// </summary>
  41. private readonly ILogger _logger;
  42. /// <summary>
  43. /// The _json serializer
  44. /// </summary>
  45. private readonly IJsonSerializer _jsonSerializer;
  46. /// <summary>
  47. /// Gets or sets the receive action.
  48. /// </summary>
  49. /// <value>The receive action.</value>
  50. public Action<WebSocketMessageInfo> OnReceive { get; set; }
  51. /// <summary>
  52. /// Gets the last activity date.
  53. /// </summary>
  54. /// <value>The last activity date.</value>
  55. public DateTime LastActivityDate { get; private set; }
  56. /// <summary>
  57. /// Gets the id.
  58. /// </summary>
  59. /// <value>The id.</value>
  60. public Guid Id { get; private set; }
  61. /// <summary>
  62. /// Gets or sets the URL.
  63. /// </summary>
  64. /// <value>The URL.</value>
  65. public string Url { get; set; }
  66. /// <summary>
  67. /// Gets or sets the query string.
  68. /// </summary>
  69. /// <value>The query string.</value>
  70. public NameValueCollection QueryString { get; set; }
  71. private readonly IMemoryStreamProvider _memoryStreamProvider;
  72. /// <summary>
  73. /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
  74. /// </summary>
  75. /// <param name="socket">The socket.</param>
  76. /// <param name="remoteEndPoint">The remote end point.</param>
  77. /// <param name="jsonSerializer">The json serializer.</param>
  78. /// <param name="logger">The logger.</param>
  79. /// <exception cref="System.ArgumentNullException">socket</exception>
  80. public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger, IMemoryStreamProvider memoryStreamProvider)
  81. {
  82. if (socket == null)
  83. {
  84. throw new ArgumentNullException("socket");
  85. }
  86. if (string.IsNullOrEmpty(remoteEndPoint))
  87. {
  88. throw new ArgumentNullException("remoteEndPoint");
  89. }
  90. if (jsonSerializer == null)
  91. {
  92. throw new ArgumentNullException("jsonSerializer");
  93. }
  94. if (logger == null)
  95. {
  96. throw new ArgumentNullException("logger");
  97. }
  98. Id = Guid.NewGuid();
  99. _jsonSerializer = jsonSerializer;
  100. _socket = socket;
  101. _socket.OnReceiveBytes = OnReceiveInternal;
  102. _socket.OnReceive = OnReceiveInternal;
  103. RemoteEndPoint = remoteEndPoint;
  104. _logger = logger;
  105. _memoryStreamProvider = memoryStreamProvider;
  106. socket.Closed += socket_Closed;
  107. }
  108. void socket_Closed(object sender, EventArgs e)
  109. {
  110. EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
  111. }
  112. /// <summary>
  113. /// Called when [receive].
  114. /// </summary>
  115. /// <param name="bytes">The bytes.</param>
  116. private void OnReceiveInternal(byte[] bytes)
  117. {
  118. LastActivityDate = DateTime.UtcNow;
  119. if (OnReceive == null)
  120. {
  121. return;
  122. }
  123. var charset = DetectCharset(bytes);
  124. if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
  125. {
  126. OnReceiveInternal(Encoding.UTF8.GetString(bytes));
  127. }
  128. else
  129. {
  130. OnReceiveInternal(Encoding.ASCII.GetString(bytes));
  131. }
  132. }
  133. private string DetectCharset(byte[] bytes)
  134. {
  135. try
  136. {
  137. using (var ms = _memoryStreamProvider.CreateNew(bytes))
  138. {
  139. var detector = new CharsetDetector();
  140. detector.Feed(ms);
  141. detector.DataEnd();
  142. var charset = detector.Charset;
  143. if (!string.IsNullOrWhiteSpace(charset))
  144. {
  145. //_logger.Debug("UniversalDetector detected charset {0}", charset);
  146. }
  147. return charset;
  148. }
  149. }
  150. catch (IOException ex)
  151. {
  152. _logger.ErrorException("Error attempting to determine web socket message charset", ex);
  153. }
  154. return null;
  155. }
  156. private void OnReceiveInternal(string message)
  157. {
  158. LastActivityDate = DateTime.UtcNow;
  159. if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
  160. {
  161. // This info is useful sometimes but also clogs up the log
  162. //_logger.Error("Received web socket message that is not a json structure: " + message);
  163. return;
  164. }
  165. if (OnReceive == null)
  166. {
  167. return;
  168. }
  169. try
  170. {
  171. var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
  172. var info = new WebSocketMessageInfo
  173. {
  174. MessageType = stub.MessageType,
  175. Data = stub.Data == null ? null : stub.Data.ToString(),
  176. Connection = this
  177. };
  178. OnReceive(info);
  179. }
  180. catch (Exception ex)
  181. {
  182. _logger.ErrorException("Error processing web socket message", ex);
  183. }
  184. }
  185. /// <summary>
  186. /// Sends a message asynchronously.
  187. /// </summary>
  188. /// <typeparam name="T"></typeparam>
  189. /// <param name="message">The message.</param>
  190. /// <param name="cancellationToken">The cancellation token.</param>
  191. /// <returns>Task.</returns>
  192. /// <exception cref="System.ArgumentNullException">message</exception>
  193. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  194. {
  195. if (message == null)
  196. {
  197. throw new ArgumentNullException("message");
  198. }
  199. var json = _jsonSerializer.SerializeToString(message);
  200. return SendAsync(json, cancellationToken);
  201. }
  202. /// <summary>
  203. /// Sends a message asynchronously.
  204. /// </summary>
  205. /// <param name="buffer">The buffer.</param>
  206. /// <param name="cancellationToken">The cancellation token.</param>
  207. /// <returns>Task.</returns>
  208. public async Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
  209. {
  210. if (buffer == null)
  211. {
  212. throw new ArgumentNullException("buffer");
  213. }
  214. cancellationToken.ThrowIfCancellationRequested();
  215. // Per msdn docs, attempting to send simultaneous messages will result in one failing.
  216. // This should help us workaround that and ensure all messages get sent
  217. await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  218. try
  219. {
  220. await _socket.SendAsync(buffer, true, cancellationToken);
  221. }
  222. catch (OperationCanceledException)
  223. {
  224. _logger.Info("WebSocket message to {0} was cancelled", RemoteEndPoint);
  225. throw;
  226. }
  227. catch (Exception ex)
  228. {
  229. _logger.ErrorException("Error sending WebSocket message {0}", ex, RemoteEndPoint);
  230. throw;
  231. }
  232. finally
  233. {
  234. _sendSemaphore.Release();
  235. }
  236. }
  237. public async Task SendAsync(string text, CancellationToken cancellationToken)
  238. {
  239. if (string.IsNullOrWhiteSpace(text))
  240. {
  241. throw new ArgumentNullException("text");
  242. }
  243. cancellationToken.ThrowIfCancellationRequested();
  244. // Per msdn docs, attempting to send simultaneous messages will result in one failing.
  245. // This should help us workaround that and ensure all messages get sent
  246. await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  247. try
  248. {
  249. await _socket.SendAsync(text, true, cancellationToken);
  250. }
  251. catch (OperationCanceledException)
  252. {
  253. _logger.Info("WebSocket message to {0} was cancelled", RemoteEndPoint);
  254. throw;
  255. }
  256. catch (Exception ex)
  257. {
  258. _logger.ErrorException("Error sending WebSocket message {0}", ex, RemoteEndPoint);
  259. throw;
  260. }
  261. finally
  262. {
  263. _sendSemaphore.Release();
  264. }
  265. }
  266. /// <summary>
  267. /// Gets the state.
  268. /// </summary>
  269. /// <value>The state.</value>
  270. public WebSocketState State
  271. {
  272. get { return _socket.State; }
  273. }
  274. /// <summary>
  275. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  276. /// </summary>
  277. public void Dispose()
  278. {
  279. Dispose(true);
  280. GC.SuppressFinalize(this);
  281. }
  282. /// <summary>
  283. /// Releases unmanaged and - optionally - managed resources.
  284. /// </summary>
  285. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  286. protected virtual void Dispose(bool dispose)
  287. {
  288. if (dispose)
  289. {
  290. _cancellationTokenSource.Dispose();
  291. _socket.Dispose();
  292. }
  293. }
  294. }
  295. }