WebSocketConnection.cs 9.1 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.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Model.Services;
  11. using MediaBrowser.Model.Text;
  12. using System.Net.WebSockets;
  13. using Emby.Server.Implementations.Net;
  14. namespace Emby.Server.Implementations.HttpServer
  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 logger
  32. /// </summary>
  33. private readonly ILogger _logger;
  34. /// <summary>
  35. /// The _json serializer
  36. /// </summary>
  37. private readonly IJsonSerializer _jsonSerializer;
  38. /// <summary>
  39. /// Gets or sets the receive action.
  40. /// </summary>
  41. /// <value>The receive action.</value>
  42. public Func<WebSocketMessageInfo, Task> OnReceive { get; set; }
  43. /// <summary>
  44. /// Gets the last activity date.
  45. /// </summary>
  46. /// <value>The last activity date.</value>
  47. public DateTime LastActivityDate { get; private set; }
  48. /// <summary>
  49. /// Gets the id.
  50. /// </summary>
  51. /// <value>The id.</value>
  52. public Guid Id { get; private set; }
  53. /// <summary>
  54. /// Gets or sets the URL.
  55. /// </summary>
  56. /// <value>The URL.</value>
  57. public string Url { get; set; }
  58. /// <summary>
  59. /// Gets or sets the query string.
  60. /// </summary>
  61. /// <value>The query string.</value>
  62. public QueryParamCollection QueryString { get; set; }
  63. private readonly ITextEncoding _textEncoding;
  64. /// <summary>
  65. /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
  66. /// </summary>
  67. /// <param name="socket">The socket.</param>
  68. /// <param name="remoteEndPoint">The remote end point.</param>
  69. /// <param name="jsonSerializer">The json serializer.</param>
  70. /// <param name="logger">The logger.</param>
  71. /// <exception cref="System.ArgumentNullException">socket</exception>
  72. public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger, ITextEncoding textEncoding)
  73. {
  74. if (socket == null)
  75. {
  76. throw new ArgumentNullException("socket");
  77. }
  78. if (string.IsNullOrEmpty(remoteEndPoint))
  79. {
  80. throw new ArgumentNullException("remoteEndPoint");
  81. }
  82. if (jsonSerializer == null)
  83. {
  84. throw new ArgumentNullException("jsonSerializer");
  85. }
  86. if (logger == null)
  87. {
  88. throw new ArgumentNullException("logger");
  89. }
  90. Id = Guid.NewGuid();
  91. _jsonSerializer = jsonSerializer;
  92. _socket = socket;
  93. _socket.OnReceiveBytes = OnReceiveInternal;
  94. var memorySocket = socket as IMemoryWebSocket;
  95. if (memorySocket != null)
  96. {
  97. memorySocket.OnReceiveMemoryBytes = OnReceiveInternal;
  98. }
  99. RemoteEndPoint = remoteEndPoint;
  100. _logger = logger;
  101. _textEncoding = textEncoding;
  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 = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, null, false);
  120. if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
  121. {
  122. OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
  123. }
  124. else
  125. {
  126. OnReceiveInternal(_textEncoding.GetASCIIEncoding().GetString(bytes, 0, bytes.Length));
  127. }
  128. }
  129. /// <summary>
  130. /// Called when [receive].
  131. /// </summary>
  132. /// <param name="bytes">The bytes.</param>
  133. private void OnReceiveInternal(Memory<byte> memory, int length)
  134. {
  135. LastActivityDate = DateTime.UtcNow;
  136. if (OnReceive == null)
  137. {
  138. return;
  139. }
  140. var bytes = memory.Slice(0, length).ToArray();
  141. var charset = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, null, false);
  142. if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
  143. {
  144. OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
  145. }
  146. else
  147. {
  148. OnReceiveInternal(_textEncoding.GetASCIIEncoding().GetString(bytes, 0, bytes.Length));
  149. }
  150. }
  151. private void OnReceiveInternal(string message)
  152. {
  153. LastActivityDate = DateTime.UtcNow;
  154. if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
  155. {
  156. // This info is useful sometimes but also clogs up the log
  157. //_logger.Error("Received web socket message that is not a json structure: " + message);
  158. return;
  159. }
  160. if (OnReceive == null)
  161. {
  162. return;
  163. }
  164. try
  165. {
  166. var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
  167. var info = new WebSocketMessageInfo
  168. {
  169. MessageType = stub.MessageType,
  170. Data = stub.Data == null ? null : stub.Data.ToString(),
  171. Connection = this
  172. };
  173. OnReceive(info);
  174. }
  175. catch (Exception ex)
  176. {
  177. _logger.ErrorException("Error processing web socket message", ex);
  178. }
  179. }
  180. /// <summary>
  181. /// Sends a message asynchronously.
  182. /// </summary>
  183. /// <typeparam name="T"></typeparam>
  184. /// <param name="message">The message.</param>
  185. /// <param name="cancellationToken">The cancellation token.</param>
  186. /// <returns>Task.</returns>
  187. /// <exception cref="System.ArgumentNullException">message</exception>
  188. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  189. {
  190. if (message == null)
  191. {
  192. throw new ArgumentNullException("message");
  193. }
  194. var json = _jsonSerializer.SerializeToString(message);
  195. return SendAsync(json, cancellationToken);
  196. }
  197. /// <summary>
  198. /// Sends a message asynchronously.
  199. /// </summary>
  200. /// <param name="buffer">The buffer.</param>
  201. /// <param name="cancellationToken">The cancellation token.</param>
  202. /// <returns>Task.</returns>
  203. public Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
  204. {
  205. if (buffer == null)
  206. {
  207. throw new ArgumentNullException("buffer");
  208. }
  209. cancellationToken.ThrowIfCancellationRequested();
  210. return _socket.SendAsync(buffer, true, cancellationToken);
  211. }
  212. public Task SendAsync(string text, CancellationToken cancellationToken)
  213. {
  214. if (string.IsNullOrEmpty(text))
  215. {
  216. throw new ArgumentNullException("text");
  217. }
  218. cancellationToken.ThrowIfCancellationRequested();
  219. return _socket.SendAsync(text, true, cancellationToken);
  220. }
  221. /// <summary>
  222. /// Gets the state.
  223. /// </summary>
  224. /// <value>The state.</value>
  225. public WebSocketState State
  226. {
  227. get { return _socket.State; }
  228. }
  229. /// <summary>
  230. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  231. /// </summary>
  232. public void Dispose()
  233. {
  234. Dispose(true);
  235. }
  236. /// <summary>
  237. /// Releases unmanaged and - optionally - managed resources.
  238. /// </summary>
  239. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  240. protected virtual void Dispose(bool dispose)
  241. {
  242. if (dispose)
  243. {
  244. _socket.Dispose();
  245. }
  246. }
  247. }
  248. }