WebSocketConnection.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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 logger
  36. /// </summary>
  37. private readonly ILogger _logger;
  38. /// <summary>
  39. /// The _json serializer
  40. /// </summary>
  41. private readonly IJsonSerializer _jsonSerializer;
  42. /// <summary>
  43. /// Gets or sets the receive action.
  44. /// </summary>
  45. /// <value>The receive action.</value>
  46. public Action<WebSocketMessageInfo> OnReceive { get; set; }
  47. /// <summary>
  48. /// Gets the last activity date.
  49. /// </summary>
  50. /// <value>The last activity date.</value>
  51. public DateTime LastActivityDate { get; private set; }
  52. /// <summary>
  53. /// Gets the id.
  54. /// </summary>
  55. /// <value>The id.</value>
  56. public Guid Id { get; private set; }
  57. /// <summary>
  58. /// Gets or sets the URL.
  59. /// </summary>
  60. /// <value>The URL.</value>
  61. public string Url { get; set; }
  62. /// <summary>
  63. /// Gets or sets the query string.
  64. /// </summary>
  65. /// <value>The query string.</value>
  66. public NameValueCollection QueryString { get; set; }
  67. private readonly IMemoryStreamProvider _memoryStreamProvider;
  68. /// <summary>
  69. /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
  70. /// </summary>
  71. /// <param name="socket">The socket.</param>
  72. /// <param name="remoteEndPoint">The remote end point.</param>
  73. /// <param name="jsonSerializer">The json serializer.</param>
  74. /// <param name="logger">The logger.</param>
  75. /// <exception cref="System.ArgumentNullException">socket</exception>
  76. public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger, IMemoryStreamProvider memoryStreamProvider)
  77. {
  78. if (socket == null)
  79. {
  80. throw new ArgumentNullException("socket");
  81. }
  82. if (string.IsNullOrEmpty(remoteEndPoint))
  83. {
  84. throw new ArgumentNullException("remoteEndPoint");
  85. }
  86. if (jsonSerializer == null)
  87. {
  88. throw new ArgumentNullException("jsonSerializer");
  89. }
  90. if (logger == null)
  91. {
  92. throw new ArgumentNullException("logger");
  93. }
  94. Id = Guid.NewGuid();
  95. _jsonSerializer = jsonSerializer;
  96. _socket = socket;
  97. _socket.OnReceiveBytes = OnReceiveInternal;
  98. _socket.OnReceive = OnReceiveInternal;
  99. RemoteEndPoint = remoteEndPoint;
  100. _logger = logger;
  101. _memoryStreamProvider = memoryStreamProvider;
  102. socket.Closed += socket_Closed;
  103. }
  104. void socket_Closed(object sender, EventArgs e)
  105. {
  106. EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
  107. }
  108. /// <summary>
  109. /// Called when [receive].
  110. /// </summary>
  111. /// <param name="bytes">The bytes.</param>
  112. private void OnReceiveInternal(byte[] bytes)
  113. {
  114. LastActivityDate = DateTime.UtcNow;
  115. if (OnReceive == null)
  116. {
  117. return;
  118. }
  119. var charset = DetectCharset(bytes);
  120. if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
  121. {
  122. OnReceiveInternal(Encoding.UTF8.GetString(bytes));
  123. }
  124. else
  125. {
  126. OnReceiveInternal(Encoding.ASCII.GetString(bytes));
  127. }
  128. }
  129. private string DetectCharset(byte[] bytes)
  130. {
  131. try
  132. {
  133. using (var ms = _memoryStreamProvider.CreateNew(bytes))
  134. {
  135. var detector = new CharsetDetector();
  136. detector.Feed(ms);
  137. detector.DataEnd();
  138. var charset = detector.Charset;
  139. if (!string.IsNullOrWhiteSpace(charset))
  140. {
  141. //_logger.Debug("UniversalDetector detected charset {0}", charset);
  142. }
  143. return charset;
  144. }
  145. }
  146. catch (IOException ex)
  147. {
  148. _logger.ErrorException("Error attempting to determine web socket message charset", ex);
  149. }
  150. return null;
  151. }
  152. private void OnReceiveInternal(string message)
  153. {
  154. LastActivityDate = DateTime.UtcNow;
  155. if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
  156. {
  157. // This info is useful sometimes but also clogs up the log
  158. //_logger.Error("Received web socket message that is not a json structure: " + message);
  159. return;
  160. }
  161. if (OnReceive == null)
  162. {
  163. return;
  164. }
  165. try
  166. {
  167. var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
  168. var info = new WebSocketMessageInfo
  169. {
  170. MessageType = stub.MessageType,
  171. Data = stub.Data == null ? null : stub.Data.ToString(),
  172. Connection = this
  173. };
  174. OnReceive(info);
  175. }
  176. catch (Exception ex)
  177. {
  178. _logger.ErrorException("Error processing web socket message", ex);
  179. }
  180. }
  181. /// <summary>
  182. /// Sends a message asynchronously.
  183. /// </summary>
  184. /// <typeparam name="T"></typeparam>
  185. /// <param name="message">The message.</param>
  186. /// <param name="cancellationToken">The cancellation token.</param>
  187. /// <returns>Task.</returns>
  188. /// <exception cref="System.ArgumentNullException">message</exception>
  189. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  190. {
  191. if (message == null)
  192. {
  193. throw new ArgumentNullException("message");
  194. }
  195. var json = _jsonSerializer.SerializeToString(message);
  196. return SendAsync(json, cancellationToken);
  197. }
  198. /// <summary>
  199. /// Sends a message asynchronously.
  200. /// </summary>
  201. /// <param name="buffer">The buffer.</param>
  202. /// <param name="cancellationToken">The cancellation token.</param>
  203. /// <returns>Task.</returns>
  204. public Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
  205. {
  206. if (buffer == null)
  207. {
  208. throw new ArgumentNullException("buffer");
  209. }
  210. cancellationToken.ThrowIfCancellationRequested();
  211. return _socket.SendAsync(buffer, true, cancellationToken);
  212. }
  213. public Task SendAsync(string text, CancellationToken cancellationToken)
  214. {
  215. if (string.IsNullOrWhiteSpace(text))
  216. {
  217. throw new ArgumentNullException("text");
  218. }
  219. cancellationToken.ThrowIfCancellationRequested();
  220. return _socket.SendAsync(text, true, cancellationToken);
  221. }
  222. /// <summary>
  223. /// Gets the state.
  224. /// </summary>
  225. /// <value>The state.</value>
  226. public WebSocketState State
  227. {
  228. get { return _socket.State; }
  229. }
  230. /// <summary>
  231. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  232. /// </summary>
  233. public void Dispose()
  234. {
  235. Dispose(true);
  236. GC.SuppressFinalize(this);
  237. }
  238. /// <summary>
  239. /// Releases unmanaged and - optionally - managed resources.
  240. /// </summary>
  241. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  242. protected virtual void Dispose(bool dispose)
  243. {
  244. if (dispose)
  245. {
  246. _cancellationTokenSource.Dispose();
  247. _socket.Dispose();
  248. }
  249. }
  250. }
  251. }