WebSocketConnection.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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 MediaBrowser.Model.IO;
  14. using MediaBrowser.Model.Services;
  15. using MediaBrowser.Model.Text;
  16. using UniversalDetector;
  17. namespace Emby.Server.Implementations.ServerManager
  18. {
  19. /// <summary>
  20. /// Class WebSocketConnection
  21. /// </summary>
  22. public class WebSocketConnection : IWebSocketConnection
  23. {
  24. public event EventHandler<EventArgs> Closed;
  25. /// <summary>
  26. /// The _socket
  27. /// </summary>
  28. private readonly IWebSocket _socket;
  29. /// <summary>
  30. /// The _remote end point
  31. /// </summary>
  32. public string RemoteEndPoint { get; private set; }
  33. /// <summary>
  34. /// The _cancellation token source
  35. /// </summary>
  36. private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
  37. /// <summary>
  38. /// The logger
  39. /// </summary>
  40. private readonly ILogger _logger;
  41. /// <summary>
  42. /// The _json serializer
  43. /// </summary>
  44. private readonly IJsonSerializer _jsonSerializer;
  45. /// <summary>
  46. /// Gets or sets the receive action.
  47. /// </summary>
  48. /// <value>The receive action.</value>
  49. public Action<WebSocketMessageInfo> OnReceive { get; set; }
  50. /// <summary>
  51. /// Gets the last activity date.
  52. /// </summary>
  53. /// <value>The last activity date.</value>
  54. public DateTime LastActivityDate { get; private set; }
  55. /// <summary>
  56. /// Gets the id.
  57. /// </summary>
  58. /// <value>The id.</value>
  59. public Guid Id { get; private set; }
  60. /// <summary>
  61. /// Gets or sets the URL.
  62. /// </summary>
  63. /// <value>The URL.</value>
  64. public string Url { get; set; }
  65. /// <summary>
  66. /// Gets or sets the query string.
  67. /// </summary>
  68. /// <value>The query string.</value>
  69. public QueryParamCollection QueryString { get; set; }
  70. private readonly IMemoryStreamFactory _memoryStreamProvider;
  71. private readonly ITextEncoding _textEncoding;
  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, IMemoryStreamFactory memoryStreamProvider, ITextEncoding textEncoding)
  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. _textEncoding = textEncoding;
  107. socket.Closed += socket_Closed;
  108. }
  109. void socket_Closed(object sender, EventArgs e)
  110. {
  111. EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
  112. }
  113. /// <summary>
  114. /// Called when [receive].
  115. /// </summary>
  116. /// <param name="bytes">The bytes.</param>
  117. private void OnReceiveInternal(byte[] bytes)
  118. {
  119. LastActivityDate = DateTime.UtcNow;
  120. if (OnReceive == null)
  121. {
  122. return;
  123. }
  124. var charset = DetectCharset(bytes);
  125. if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
  126. {
  127. OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
  128. }
  129. else
  130. {
  131. OnReceiveInternal(_textEncoding.GetASCIIEncoding().GetString(bytes, 0, bytes.Length));
  132. }
  133. }
  134. private string DetectCharset(byte[] bytes)
  135. {
  136. try
  137. {
  138. using (var ms = _memoryStreamProvider.CreateNew(bytes))
  139. {
  140. var detector = new CharsetDetector();
  141. detector.Feed(ms);
  142. detector.DataEnd();
  143. var charset = detector.Charset;
  144. if (!string.IsNullOrWhiteSpace(charset))
  145. {
  146. //_logger.Debug("UniversalDetector detected charset {0}", charset);
  147. }
  148. return charset;
  149. }
  150. }
  151. catch (IOException ex)
  152. {
  153. _logger.ErrorException("Error attempting to determine web socket message charset", ex);
  154. }
  155. return null;
  156. }
  157. private void OnReceiveInternal(string message)
  158. {
  159. LastActivityDate = DateTime.UtcNow;
  160. if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
  161. {
  162. // This info is useful sometimes but also clogs up the log
  163. //_logger.Error("Received web socket message that is not a json structure: " + message);
  164. return;
  165. }
  166. if (OnReceive == null)
  167. {
  168. return;
  169. }
  170. try
  171. {
  172. var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
  173. var info = new WebSocketMessageInfo
  174. {
  175. MessageType = stub.MessageType,
  176. Data = stub.Data == null ? null : stub.Data.ToString(),
  177. Connection = this
  178. };
  179. OnReceive(info);
  180. }
  181. catch (Exception ex)
  182. {
  183. _logger.ErrorException("Error processing web socket message", ex);
  184. }
  185. }
  186. /// <summary>
  187. /// Sends a message asynchronously.
  188. /// </summary>
  189. /// <typeparam name="T"></typeparam>
  190. /// <param name="message">The message.</param>
  191. /// <param name="cancellationToken">The cancellation token.</param>
  192. /// <returns>Task.</returns>
  193. /// <exception cref="System.ArgumentNullException">message</exception>
  194. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  195. {
  196. if (message == null)
  197. {
  198. throw new ArgumentNullException("message");
  199. }
  200. var json = _jsonSerializer.SerializeToString(message);
  201. return SendAsync(json, cancellationToken);
  202. }
  203. /// <summary>
  204. /// Sends a message asynchronously.
  205. /// </summary>
  206. /// <param name="buffer">The buffer.</param>
  207. /// <param name="cancellationToken">The cancellation token.</param>
  208. /// <returns>Task.</returns>
  209. public Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
  210. {
  211. if (buffer == null)
  212. {
  213. throw new ArgumentNullException("buffer");
  214. }
  215. cancellationToken.ThrowIfCancellationRequested();
  216. return _socket.SendAsync(buffer, true, cancellationToken);
  217. }
  218. public Task SendAsync(string text, CancellationToken cancellationToken)
  219. {
  220. if (string.IsNullOrWhiteSpace(text))
  221. {
  222. throw new ArgumentNullException("text");
  223. }
  224. cancellationToken.ThrowIfCancellationRequested();
  225. return _socket.SendAsync(text, true, cancellationToken);
  226. }
  227. /// <summary>
  228. /// Gets the state.
  229. /// </summary>
  230. /// <value>The state.</value>
  231. public WebSocketState State
  232. {
  233. get { return _socket.State; }
  234. }
  235. /// <summary>
  236. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  237. /// </summary>
  238. public void Dispose()
  239. {
  240. Dispose(true);
  241. GC.SuppressFinalize(this);
  242. }
  243. /// <summary>
  244. /// Releases unmanaged and - optionally - managed resources.
  245. /// </summary>
  246. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  247. protected virtual void Dispose(bool dispose)
  248. {
  249. if (dispose)
  250. {
  251. _cancellationTokenSource.Dispose();
  252. _socket.Dispose();
  253. }
  254. }
  255. }
  256. }