2
0

WebSocketConnection.cs 9.2 KB

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