WebSocketConnection.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. using System;
  2. using System.Net.WebSockets;
  3. using System.Text;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Emby.Server.Implementations.Net;
  7. using MediaBrowser.Controller.Net;
  8. using MediaBrowser.Model.Net;
  9. using MediaBrowser.Model.Serialization;
  10. using Microsoft.AspNetCore.Http;
  11. using Microsoft.Extensions.Logging;
  12. using UtfUnknown;
  13. namespace Emby.Server.Implementations.HttpServer
  14. {
  15. /// <summary>
  16. /// Class WebSocketConnection.
  17. /// </summary>
  18. public class WebSocketConnection : IWebSocketConnection
  19. {
  20. /// <summary>
  21. /// The logger.
  22. /// </summary>
  23. private readonly ILogger _logger;
  24. /// <summary>
  25. /// The json serializer.
  26. /// </summary>
  27. private readonly IJsonSerializer _jsonSerializer;
  28. /// <summary>
  29. /// The socket.
  30. /// </summary>
  31. private readonly IWebSocket _socket;
  32. /// <summary>
  33. /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
  34. /// </summary>
  35. /// <param name="socket">The socket.</param>
  36. /// <param name="remoteEndPoint">The remote end point.</param>
  37. /// <param name="jsonSerializer">The json serializer.</param>
  38. /// <param name="logger">The logger.</param>
  39. /// <exception cref="ArgumentNullException">socket</exception>
  40. public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger)
  41. {
  42. if (socket == null)
  43. {
  44. throw new ArgumentNullException(nameof(socket));
  45. }
  46. if (string.IsNullOrEmpty(remoteEndPoint))
  47. {
  48. throw new ArgumentNullException(nameof(remoteEndPoint));
  49. }
  50. if (jsonSerializer == null)
  51. {
  52. throw new ArgumentNullException(nameof(jsonSerializer));
  53. }
  54. if (logger == null)
  55. {
  56. throw new ArgumentNullException(nameof(logger));
  57. }
  58. Id = Guid.NewGuid();
  59. _jsonSerializer = jsonSerializer;
  60. _socket = socket;
  61. _socket.OnReceiveBytes = OnReceiveInternal;
  62. RemoteEndPoint = remoteEndPoint;
  63. _logger = logger;
  64. socket.Closed += OnSocketClosed;
  65. }
  66. /// <inheritdoc />
  67. public event EventHandler<EventArgs> Closed;
  68. /// <summary>
  69. /// Gets or sets the remote end point.
  70. /// </summary>
  71. public string RemoteEndPoint { get; private set; }
  72. /// <summary>
  73. /// Gets or sets the receive action.
  74. /// </summary>
  75. /// <value>The receive action.</value>
  76. public Func<WebSocketMessageInfo, Task> OnReceive { get; set; }
  77. /// <summary>
  78. /// Gets the last activity date.
  79. /// </summary>
  80. /// <value>The last activity date.</value>
  81. public DateTime LastActivityDate { get; private set; }
  82. /// <summary>
  83. /// Gets the id.
  84. /// </summary>
  85. /// <value>The id.</value>
  86. public Guid Id { get; private set; }
  87. /// <summary>
  88. /// Gets or sets the URL.
  89. /// </summary>
  90. /// <value>The URL.</value>
  91. public string Url { get; set; }
  92. /// <summary>
  93. /// Gets or sets the query string.
  94. /// </summary>
  95. /// <value>The query string.</value>
  96. public IQueryCollection QueryString { get; set; }
  97. /// <summary>
  98. /// Gets the state.
  99. /// </summary>
  100. /// <value>The state.</value>
  101. public WebSocketState State => _socket.State;
  102. void OnSocketClosed(object sender, EventArgs e)
  103. {
  104. Closed?.Invoke(this, EventArgs.Empty);
  105. }
  106. /// <summary>
  107. /// Called when [receive].
  108. /// </summary>
  109. /// <param name="bytes">The bytes.</param>
  110. private void OnReceiveInternal(byte[] bytes)
  111. {
  112. LastActivityDate = DateTime.UtcNow;
  113. if (OnReceive == null)
  114. {
  115. return;
  116. }
  117. var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName;
  118. if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
  119. {
  120. OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
  121. }
  122. else
  123. {
  124. OnReceiveInternal(Encoding.ASCII.GetString(bytes, 0, bytes.Length));
  125. }
  126. }
  127. private void OnReceiveInternal(string message)
  128. {
  129. LastActivityDate = DateTime.UtcNow;
  130. if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
  131. {
  132. // This info is useful sometimes but also clogs up the log
  133. _logger.LogDebug("Received web socket message that is not a json structure: {message}", message);
  134. return;
  135. }
  136. if (OnReceive == null)
  137. {
  138. return;
  139. }
  140. try
  141. {
  142. var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
  143. var info = new WebSocketMessageInfo
  144. {
  145. MessageType = stub.MessageType,
  146. Data = stub.Data?.ToString(),
  147. Connection = this
  148. };
  149. OnReceive(info);
  150. }
  151. catch (Exception ex)
  152. {
  153. _logger.LogError(ex, "Error processing web socket message");
  154. }
  155. }
  156. /// <summary>
  157. /// Sends a message asynchronously.
  158. /// </summary>
  159. /// <typeparam name="T"></typeparam>
  160. /// <param name="message">The message.</param>
  161. /// <param name="cancellationToken">The cancellation token.</param>
  162. /// <returns>Task.</returns>
  163. /// <exception cref="ArgumentNullException">message</exception>
  164. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  165. {
  166. if (message == null)
  167. {
  168. throw new ArgumentNullException(nameof(message));
  169. }
  170. var json = _jsonSerializer.SerializeToString(message);
  171. return SendAsync(json, cancellationToken);
  172. }
  173. /// <summary>
  174. /// Sends a message asynchronously.
  175. /// </summary>
  176. /// <param name="buffer">The buffer.</param>
  177. /// <param name="cancellationToken">The cancellation token.</param>
  178. /// <returns>Task.</returns>
  179. public Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
  180. {
  181. if (buffer == null)
  182. {
  183. throw new ArgumentNullException(nameof(buffer));
  184. }
  185. cancellationToken.ThrowIfCancellationRequested();
  186. return _socket.SendAsync(buffer, true, cancellationToken);
  187. }
  188. /// <inheritdoc />
  189. public Task SendAsync(string text, CancellationToken cancellationToken)
  190. {
  191. if (string.IsNullOrEmpty(text))
  192. {
  193. throw new ArgumentNullException(nameof(text));
  194. }
  195. cancellationToken.ThrowIfCancellationRequested();
  196. return _socket.SendAsync(text, true, cancellationToken);
  197. }
  198. /// <inheritdoc />
  199. public void Dispose()
  200. {
  201. Dispose(true);
  202. GC.SuppressFinalize(this);
  203. }
  204. /// <summary>
  205. /// Releases unmanaged and - optionally - managed resources.
  206. /// </summary>
  207. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  208. protected virtual void Dispose(bool dispose)
  209. {
  210. if (dispose)
  211. {
  212. _socket.Dispose();
  213. }
  214. }
  215. }
  216. }