WebSocketConnection.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. using System.Text;
  2. using MediaBrowser.Controller.Net;
  3. using Microsoft.Extensions.Logging;
  4. using MediaBrowser.Model.Net;
  5. using MediaBrowser.Model.Serialization;
  6. using System;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Model.Services;
  10. using MediaBrowser.Model.Text;
  11. using System.Net.WebSockets;
  12. using Emby.Server.Implementations.Net;
  13. namespace Emby.Server.Implementations.HttpServer
  14. {
  15. /// <summary>
  16. /// Class WebSocketConnection
  17. /// </summary>
  18. public class WebSocketConnection : IWebSocketConnection
  19. {
  20. public event EventHandler<EventArgs> Closed;
  21. /// <summary>
  22. /// The _socket
  23. /// </summary>
  24. private readonly IWebSocket _socket;
  25. /// <summary>
  26. /// The _remote end point
  27. /// </summary>
  28. public string RemoteEndPoint { get; private set; }
  29. /// <summary>
  30. /// The logger
  31. /// </summary>
  32. private readonly ILogger _logger;
  33. /// <summary>
  34. /// The _json serializer
  35. /// </summary>
  36. private readonly IJsonSerializer _jsonSerializer;
  37. /// <summary>
  38. /// Gets or sets the receive action.
  39. /// </summary>
  40. /// <value>The receive action.</value>
  41. public Func<WebSocketMessageInfo, Task> OnReceive { get; set; }
  42. /// <summary>
  43. /// Gets the last activity date.
  44. /// </summary>
  45. /// <value>The last activity date.</value>
  46. public DateTime LastActivityDate { get; private set; }
  47. /// <summary>
  48. /// Gets the id.
  49. /// </summary>
  50. /// <value>The id.</value>
  51. public Guid Id { get; private set; }
  52. /// <summary>
  53. /// Gets or sets the URL.
  54. /// </summary>
  55. /// <value>The URL.</value>
  56. public string Url { get; set; }
  57. /// <summary>
  58. /// Gets or sets the query string.
  59. /// </summary>
  60. /// <value>The query string.</value>
  61. public QueryParamCollection QueryString { get; set; }
  62. private readonly ITextEncoding _textEncoding;
  63. /// <summary>
  64. /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
  65. /// </summary>
  66. /// <param name="socket">The socket.</param>
  67. /// <param name="remoteEndPoint">The remote end point.</param>
  68. /// <param name="jsonSerializer">The json serializer.</param>
  69. /// <param name="logger">The logger.</param>
  70. /// <exception cref="System.ArgumentNullException">socket</exception>
  71. public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger, ITextEncoding textEncoding)
  72. {
  73. if (socket == null)
  74. {
  75. throw new ArgumentNullException(nameof(socket));
  76. }
  77. if (string.IsNullOrEmpty(remoteEndPoint))
  78. {
  79. throw new ArgumentNullException(nameof(remoteEndPoint));
  80. }
  81. if (jsonSerializer == null)
  82. {
  83. throw new ArgumentNullException(nameof(jsonSerializer));
  84. }
  85. if (logger == null)
  86. {
  87. throw new ArgumentNullException(nameof(logger));
  88. }
  89. Id = Guid.NewGuid();
  90. _jsonSerializer = jsonSerializer;
  91. _socket = socket;
  92. _socket.OnReceiveBytes = OnReceiveInternal;
  93. var memorySocket = socket as IMemoryWebSocket;
  94. if (memorySocket != null)
  95. {
  96. memorySocket.OnReceiveMemoryBytes = OnReceiveInternal;
  97. }
  98. RemoteEndPoint = remoteEndPoint;
  99. _logger = logger;
  100. _textEncoding = textEncoding;
  101. socket.Closed += socket_Closed;
  102. }
  103. void socket_Closed(object sender, EventArgs e)
  104. {
  105. Closed?.Invoke(this, EventArgs.Empty);
  106. }
  107. /// <summary>
  108. /// Called when [receive].
  109. /// </summary>
  110. /// <param name="bytes">The bytes.</param>
  111. private void OnReceiveInternal(byte[] bytes)
  112. {
  113. LastActivityDate = DateTime.UtcNow;
  114. if (OnReceive == null)
  115. {
  116. return;
  117. }
  118. var charset = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, null, false);
  119. if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
  120. {
  121. OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
  122. }
  123. else
  124. {
  125. OnReceiveInternal(_textEncoding.GetASCIIEncoding().GetString(bytes, 0, bytes.Length));
  126. }
  127. }
  128. /// <summary>
  129. /// Called when [receive].
  130. /// </summary>
  131. /// <param name="memory">The memory block.</param>
  132. /// <param name="length">The length of the memory block.</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.LogDebug("Received web socket message that is not a json structure: {message}", 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.LogError(ex, "Error processing web socket message");
  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(nameof(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(nameof(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(nameof(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 => _socket.State;
  226. /// <summary>
  227. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  228. /// </summary>
  229. public void Dispose()
  230. {
  231. Dispose(true);
  232. }
  233. /// <summary>
  234. /// Releases unmanaged and - optionally - managed resources.
  235. /// </summary>
  236. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  237. protected virtual void Dispose(bool dispose)
  238. {
  239. if (dispose)
  240. {
  241. _socket.Dispose();
  242. }
  243. }
  244. }
  245. }