WebSocketConnection.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. /// <inheritdoc />
  83. public DateTime LastKeepAliveDate { get; set; }
  84. /// <summary>
  85. /// Gets the id.
  86. /// </summary>
  87. /// <value>The id.</value>
  88. public Guid Id { get; private set; }
  89. /// <summary>
  90. /// Gets or sets the URL.
  91. /// </summary>
  92. /// <value>The URL.</value>
  93. public string Url { get; set; }
  94. /// <summary>
  95. /// Gets or sets the query string.
  96. /// </summary>
  97. /// <value>The query string.</value>
  98. public IQueryCollection QueryString { get; set; }
  99. /// <summary>
  100. /// Gets the state.
  101. /// </summary>
  102. /// <value>The state.</value>
  103. public WebSocketState State => _socket.State;
  104. void OnSocketClosed(object sender, EventArgs e)
  105. {
  106. Closed?.Invoke(this, EventArgs.Empty);
  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 = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName;
  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(Encoding.ASCII.GetString(bytes, 0, bytes.Length));
  127. }
  128. }
  129. private void OnReceiveInternal(string message)
  130. {
  131. LastActivityDate = DateTime.UtcNow;
  132. if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
  133. {
  134. // This info is useful sometimes but also clogs up the log
  135. _logger.LogDebug("Received web socket message that is not a json structure: {message}", message);
  136. return;
  137. }
  138. try
  139. {
  140. var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
  141. var info = new WebSocketMessageInfo
  142. {
  143. MessageType = stub.MessageType,
  144. Data = stub.Data?.ToString(),
  145. Connection = this
  146. };
  147. if (info.MessageType.Equals("KeepAlive", StringComparison.Ordinal))
  148. {
  149. SendKeepAliveResponse();
  150. }
  151. else
  152. {
  153. OnReceive?.Invoke(info);
  154. }
  155. }
  156. catch (Exception ex)
  157. {
  158. _logger.LogError(ex, "Error processing web socket message");
  159. }
  160. }
  161. /// <summary>
  162. /// Sends a message asynchronously.
  163. /// </summary>
  164. /// <typeparam name="T"></typeparam>
  165. /// <param name="message">The message.</param>
  166. /// <param name="cancellationToken">The cancellation token.</param>
  167. /// <returns>Task.</returns>
  168. /// <exception cref="ArgumentNullException">message</exception>
  169. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  170. {
  171. if (message == null)
  172. {
  173. throw new ArgumentNullException(nameof(message));
  174. }
  175. var json = _jsonSerializer.SerializeToString(message);
  176. return SendAsync(json, cancellationToken);
  177. }
  178. /// <summary>
  179. /// Sends a message asynchronously.
  180. /// </summary>
  181. /// <param name="buffer">The buffer.</param>
  182. /// <param name="cancellationToken">The cancellation token.</param>
  183. /// <returns>Task.</returns>
  184. public Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
  185. {
  186. if (buffer == null)
  187. {
  188. throw new ArgumentNullException(nameof(buffer));
  189. }
  190. cancellationToken.ThrowIfCancellationRequested();
  191. return _socket.SendAsync(buffer, true, cancellationToken);
  192. }
  193. /// <inheritdoc />
  194. public Task SendAsync(string text, CancellationToken cancellationToken)
  195. {
  196. if (string.IsNullOrEmpty(text))
  197. {
  198. throw new ArgumentNullException(nameof(text));
  199. }
  200. cancellationToken.ThrowIfCancellationRequested();
  201. return _socket.SendAsync(text, true, cancellationToken);
  202. }
  203. private Task SendKeepAliveResponse()
  204. {
  205. LastKeepAliveDate = DateTime.UtcNow;
  206. return SendAsync(new WebSocketMessage<string>
  207. {
  208. MessageType = "KeepAlive"
  209. }, CancellationToken.None);
  210. }
  211. /// <inheritdoc />
  212. public void Dispose()
  213. {
  214. Dispose(true);
  215. GC.SuppressFinalize(this);
  216. }
  217. /// <summary>
  218. /// Releases unmanaged and - optionally - managed resources.
  219. /// </summary>
  220. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  221. protected virtual void Dispose(bool dispose)
  222. {
  223. if (dispose)
  224. {
  225. _socket.Dispose();
  226. }
  227. }
  228. }
  229. }