WebSocketConnection.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. namespace Emby.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 IMemoryStreamFactory _memoryStreamProvider;
  70. private readonly ITextEncoding _textEncoding;
  71. /// <summary>
  72. /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
  73. /// </summary>
  74. /// <param name="socket">The socket.</param>
  75. /// <param name="remoteEndPoint">The remote end point.</param>
  76. /// <param name="jsonSerializer">The json serializer.</param>
  77. /// <param name="logger">The logger.</param>
  78. /// <exception cref="System.ArgumentNullException">socket</exception>
  79. public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger, IMemoryStreamFactory memoryStreamProvider, ITextEncoding textEncoding)
  80. {
  81. if (socket == null)
  82. {
  83. throw new ArgumentNullException("socket");
  84. }
  85. if (string.IsNullOrEmpty(remoteEndPoint))
  86. {
  87. throw new ArgumentNullException("remoteEndPoint");
  88. }
  89. if (jsonSerializer == null)
  90. {
  91. throw new ArgumentNullException("jsonSerializer");
  92. }
  93. if (logger == null)
  94. {
  95. throw new ArgumentNullException("logger");
  96. }
  97. Id = Guid.NewGuid();
  98. _jsonSerializer = jsonSerializer;
  99. _socket = socket;
  100. _socket.OnReceiveBytes = OnReceiveInternal;
  101. _socket.OnReceive = OnReceiveInternal;
  102. RemoteEndPoint = remoteEndPoint;
  103. _logger = logger;
  104. _memoryStreamProvider = memoryStreamProvider;
  105. _textEncoding = textEncoding;
  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 = _textEncoding.GetDetectedEncodingName(bytes, null);
  124. if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
  125. {
  126. OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
  127. }
  128. else
  129. {
  130. OnReceiveInternal(_textEncoding.GetASCIIEncoding().GetString(bytes, 0, bytes.Length));
  131. }
  132. }
  133. private void OnReceiveInternal(string message)
  134. {
  135. LastActivityDate = DateTime.UtcNow;
  136. if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
  137. {
  138. // This info is useful sometimes but also clogs up the log
  139. //_logger.Error("Received web socket message that is not a json structure: " + message);
  140. return;
  141. }
  142. if (OnReceive == null)
  143. {
  144. return;
  145. }
  146. try
  147. {
  148. var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
  149. var info = new WebSocketMessageInfo
  150. {
  151. MessageType = stub.MessageType,
  152. Data = stub.Data == null ? null : stub.Data.ToString(),
  153. Connection = this
  154. };
  155. OnReceive(info);
  156. }
  157. catch (Exception ex)
  158. {
  159. _logger.ErrorException("Error processing web socket message", ex);
  160. }
  161. }
  162. /// <summary>
  163. /// Sends a message asynchronously.
  164. /// </summary>
  165. /// <typeparam name="T"></typeparam>
  166. /// <param name="message">The message.</param>
  167. /// <param name="cancellationToken">The cancellation token.</param>
  168. /// <returns>Task.</returns>
  169. /// <exception cref="System.ArgumentNullException">message</exception>
  170. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  171. {
  172. if (message == null)
  173. {
  174. throw new ArgumentNullException("message");
  175. }
  176. var json = _jsonSerializer.SerializeToString(message);
  177. return SendAsync(json, cancellationToken);
  178. }
  179. /// <summary>
  180. /// Sends a message asynchronously.
  181. /// </summary>
  182. /// <param name="buffer">The buffer.</param>
  183. /// <param name="cancellationToken">The cancellation token.</param>
  184. /// <returns>Task.</returns>
  185. public Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
  186. {
  187. if (buffer == null)
  188. {
  189. throw new ArgumentNullException("buffer");
  190. }
  191. cancellationToken.ThrowIfCancellationRequested();
  192. return _socket.SendAsync(buffer, true, cancellationToken);
  193. }
  194. public Task SendAsync(string text, CancellationToken cancellationToken)
  195. {
  196. if (string.IsNullOrWhiteSpace(text))
  197. {
  198. throw new ArgumentNullException("text");
  199. }
  200. cancellationToken.ThrowIfCancellationRequested();
  201. return _socket.SendAsync(text, true, cancellationToken);
  202. }
  203. /// <summary>
  204. /// Gets the state.
  205. /// </summary>
  206. /// <value>The state.</value>
  207. public WebSocketState State
  208. {
  209. get { return _socket.State; }
  210. }
  211. /// <summary>
  212. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  213. /// </summary>
  214. public void Dispose()
  215. {
  216. Dispose(true);
  217. GC.SuppressFinalize(this);
  218. }
  219. /// <summary>
  220. /// Releases unmanaged and - optionally - managed resources.
  221. /// </summary>
  222. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  223. protected virtual void Dispose(bool dispose)
  224. {
  225. if (dispose)
  226. {
  227. _cancellationTokenSource.Dispose();
  228. _socket.Dispose();
  229. }
  230. }
  231. }
  232. }