WebSocketConnection.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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.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. 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. /// <summary>
  63. /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
  64. /// </summary>
  65. /// <param name="socket">The socket.</param>
  66. /// <param name="remoteEndPoint">The remote end point.</param>
  67. /// <param name="jsonSerializer">The json serializer.</param>
  68. /// <param name="logger">The logger.</param>
  69. /// <exception cref="ArgumentNullException">socket</exception>
  70. public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger)
  71. {
  72. if (socket == null)
  73. {
  74. throw new ArgumentNullException(nameof(socket));
  75. }
  76. if (string.IsNullOrEmpty(remoteEndPoint))
  77. {
  78. throw new ArgumentNullException(nameof(remoteEndPoint));
  79. }
  80. if (jsonSerializer == null)
  81. {
  82. throw new ArgumentNullException(nameof(jsonSerializer));
  83. }
  84. if (logger == null)
  85. {
  86. throw new ArgumentNullException(nameof(logger));
  87. }
  88. Id = Guid.NewGuid();
  89. _jsonSerializer = jsonSerializer;
  90. _socket = socket;
  91. _socket.OnReceiveBytes = OnReceiveInternal;
  92. var memorySocket = socket as IMemoryWebSocket;
  93. if (memorySocket != null)
  94. {
  95. memorySocket.OnReceiveMemoryBytes = OnReceiveInternal;
  96. }
  97. RemoteEndPoint = remoteEndPoint;
  98. _logger = logger;
  99. socket.Closed += socket_Closed;
  100. }
  101. void socket_Closed(object sender, EventArgs e)
  102. {
  103. Closed?.Invoke(this, EventArgs.Empty);
  104. }
  105. /// <summary>
  106. /// Called when [receive].
  107. /// </summary>
  108. /// <param name="bytes">The bytes.</param>
  109. private void OnReceiveInternal(byte[] bytes)
  110. {
  111. LastActivityDate = DateTime.UtcNow;
  112. if (OnReceive == null)
  113. {
  114. return;
  115. }
  116. var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName;
  117. if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
  118. {
  119. OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
  120. }
  121. else
  122. {
  123. OnReceiveInternal(Encoding.ASCII.GetString(bytes, 0, bytes.Length));
  124. }
  125. }
  126. /// <summary>
  127. /// Called when [receive].
  128. /// </summary>
  129. /// <param name="memory">The memory block.</param>
  130. /// <param name="length">The length of the memory block.</param>
  131. private void OnReceiveInternal(Memory<byte> memory, int length)
  132. {
  133. LastActivityDate = DateTime.UtcNow;
  134. if (OnReceive == null)
  135. {
  136. return;
  137. }
  138. var bytes = memory.Slice(0, length).ToArray();
  139. var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName;
  140. if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
  141. {
  142. OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
  143. }
  144. else
  145. {
  146. OnReceiveInternal(Encoding.ASCII.GetString(bytes, 0, bytes.Length));
  147. }
  148. }
  149. private void OnReceiveInternal(string message)
  150. {
  151. LastActivityDate = DateTime.UtcNow;
  152. if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
  153. {
  154. // This info is useful sometimes but also clogs up the log
  155. _logger.LogDebug("Received web socket message that is not a json structure: {message}", message);
  156. return;
  157. }
  158. if (OnReceive == null)
  159. {
  160. return;
  161. }
  162. try
  163. {
  164. var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
  165. var info = new WebSocketMessageInfo
  166. {
  167. MessageType = stub.MessageType,
  168. Data = stub.Data == null ? null : stub.Data.ToString(),
  169. Connection = this
  170. };
  171. OnReceive(info);
  172. }
  173. catch (Exception ex)
  174. {
  175. _logger.LogError(ex, "Error processing web socket message");
  176. }
  177. }
  178. /// <summary>
  179. /// Sends a message asynchronously.
  180. /// </summary>
  181. /// <typeparam name="T"></typeparam>
  182. /// <param name="message">The message.</param>
  183. /// <param name="cancellationToken">The cancellation token.</param>
  184. /// <returns>Task.</returns>
  185. /// <exception cref="ArgumentNullException">message</exception>
  186. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  187. {
  188. if (message == null)
  189. {
  190. throw new ArgumentNullException(nameof(message));
  191. }
  192. var json = _jsonSerializer.SerializeToString(message);
  193. return SendAsync(json, cancellationToken);
  194. }
  195. /// <summary>
  196. /// Sends a message asynchronously.
  197. /// </summary>
  198. /// <param name="buffer">The buffer.</param>
  199. /// <param name="cancellationToken">The cancellation token.</param>
  200. /// <returns>Task.</returns>
  201. public Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
  202. {
  203. if (buffer == null)
  204. {
  205. throw new ArgumentNullException(nameof(buffer));
  206. }
  207. cancellationToken.ThrowIfCancellationRequested();
  208. return _socket.SendAsync(buffer, true, cancellationToken);
  209. }
  210. public Task SendAsync(string text, CancellationToken cancellationToken)
  211. {
  212. if (string.IsNullOrEmpty(text))
  213. {
  214. throw new ArgumentNullException(nameof(text));
  215. }
  216. cancellationToken.ThrowIfCancellationRequested();
  217. return _socket.SendAsync(text, true, cancellationToken);
  218. }
  219. /// <summary>
  220. /// Gets the state.
  221. /// </summary>
  222. /// <value>The state.</value>
  223. public WebSocketState State => _socket.State;
  224. /// <summary>
  225. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  226. /// </summary>
  227. public void Dispose()
  228. {
  229. Dispose(true);
  230. }
  231. /// <summary>
  232. /// Releases unmanaged and - optionally - managed resources.
  233. /// </summary>
  234. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  235. protected virtual void Dispose(bool dispose)
  236. {
  237. if (dispose)
  238. {
  239. _socket.Dispose();
  240. }
  241. }
  242. }
  243. }