WebSocketConnection.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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 MediaBrowser.Model.Services;
  11. using Microsoft.AspNetCore.Http;
  12. using Microsoft.Extensions.Logging;
  13. using UtfUnknown;
  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 IQueryCollection QueryString { get; set; }
  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="ArgumentNullException">socket</exception>
  71. public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger)
  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. RemoteEndPoint = remoteEndPoint;
  94. _logger = logger;
  95. socket.Closed += socket_Closed;
  96. }
  97. void socket_Closed(object sender, EventArgs e)
  98. {
  99. Closed?.Invoke(this, EventArgs.Empty);
  100. }
  101. /// <summary>
  102. /// Called when [receive].
  103. /// </summary>
  104. /// <param name="bytes">The bytes.</param>
  105. private void OnReceiveInternal(byte[] bytes)
  106. {
  107. LastActivityDate = DateTime.UtcNow;
  108. if (OnReceive == null)
  109. {
  110. return;
  111. }
  112. var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName;
  113. if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
  114. {
  115. OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
  116. }
  117. else
  118. {
  119. OnReceiveInternal(Encoding.ASCII.GetString(bytes, 0, bytes.Length));
  120. }
  121. }
  122. private void OnReceiveInternal(string message)
  123. {
  124. LastActivityDate = DateTime.UtcNow;
  125. if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
  126. {
  127. // This info is useful sometimes but also clogs up the log
  128. _logger.LogDebug("Received web socket message that is not a json structure: {message}", message);
  129. return;
  130. }
  131. if (OnReceive == null)
  132. {
  133. return;
  134. }
  135. try
  136. {
  137. var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
  138. var info = new WebSocketMessageInfo
  139. {
  140. MessageType = stub.MessageType,
  141. Data = stub.Data?.ToString(),
  142. Connection = this
  143. };
  144. OnReceive(info);
  145. }
  146. catch (Exception ex)
  147. {
  148. _logger.LogError(ex, "Error processing web socket message");
  149. }
  150. }
  151. /// <summary>
  152. /// Sends a message asynchronously.
  153. /// </summary>
  154. /// <typeparam name="T"></typeparam>
  155. /// <param name="message">The message.</param>
  156. /// <param name="cancellationToken">The cancellation token.</param>
  157. /// <returns>Task.</returns>
  158. /// <exception cref="ArgumentNullException">message</exception>
  159. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  160. {
  161. if (message == null)
  162. {
  163. throw new ArgumentNullException(nameof(message));
  164. }
  165. var json = _jsonSerializer.SerializeToString(message);
  166. return SendAsync(json, cancellationToken);
  167. }
  168. /// <summary>
  169. /// Sends a message asynchronously.
  170. /// </summary>
  171. /// <param name="buffer">The buffer.</param>
  172. /// <param name="cancellationToken">The cancellation token.</param>
  173. /// <returns>Task.</returns>
  174. public Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
  175. {
  176. if (buffer == null)
  177. {
  178. throw new ArgumentNullException(nameof(buffer));
  179. }
  180. cancellationToken.ThrowIfCancellationRequested();
  181. return _socket.SendAsync(buffer, true, cancellationToken);
  182. }
  183. public Task SendAsync(string text, CancellationToken cancellationToken)
  184. {
  185. if (string.IsNullOrEmpty(text))
  186. {
  187. throw new ArgumentNullException(nameof(text));
  188. }
  189. cancellationToken.ThrowIfCancellationRequested();
  190. return _socket.SendAsync(text, true, cancellationToken);
  191. }
  192. /// <summary>
  193. /// Gets the state.
  194. /// </summary>
  195. /// <value>The state.</value>
  196. public WebSocketState State => _socket.State;
  197. /// <summary>
  198. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  199. /// </summary>
  200. public void Dispose()
  201. {
  202. Dispose(true);
  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. }