WebSocketConnection.cs 9.2 KB

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