| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338 | 
							- using System.Text;
 
- using MediaBrowser.Common.Events;
 
- using MediaBrowser.Controller.Net;
 
- using MediaBrowser.Model.Logging;
 
- using MediaBrowser.Model.Net;
 
- using MediaBrowser.Model.Serialization;
 
- using System;
 
- using System.Collections.Specialized;
 
- using System.IO;
 
- using System.Threading;
 
- using System.Threading.Tasks;
 
- using UniversalDetector;
 
- namespace MediaBrowser.Server.Implementations.ServerManager
 
- {
 
-     /// <summary>
 
-     /// Class WebSocketConnection
 
-     /// </summary>
 
-     public class WebSocketConnection : IWebSocketConnection
 
-     {
 
-         public event EventHandler<EventArgs> Closed;
 
-         
 
-         /// <summary>
 
-         /// The _socket
 
-         /// </summary>
 
-         private readonly IWebSocket _socket;
 
-         /// <summary>
 
-         /// The _remote end point
 
-         /// </summary>
 
-         public string RemoteEndPoint { get; private set; }
 
-         /// <summary>
 
-         /// The _cancellation token source
 
-         /// </summary>
 
-         private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
 
-         /// <summary>
 
-         /// The _send semaphore
 
-         /// </summary>
 
-         private readonly SemaphoreSlim _sendSemaphore = new SemaphoreSlim(1, 1);
 
-         /// <summary>
 
-         /// The logger
 
-         /// </summary>
 
-         private readonly ILogger _logger;
 
-         /// <summary>
 
-         /// The _json serializer
 
-         /// </summary>
 
-         private readonly IJsonSerializer _jsonSerializer;
 
-         /// <summary>
 
-         /// Gets or sets the receive action.
 
-         /// </summary>
 
-         /// <value>The receive action.</value>
 
-         public Action<WebSocketMessageInfo> OnReceive { get; set; }
 
-         /// <summary>
 
-         /// Gets the last activity date.
 
-         /// </summary>
 
-         /// <value>The last activity date.</value>
 
-         public DateTime LastActivityDate { get; private set; }
 
-         /// <summary>
 
-         /// Gets the id.
 
-         /// </summary>
 
-         /// <value>The id.</value>
 
-         public Guid Id { get; private set; }
 
-         /// <summary>
 
-         /// Gets or sets the URL.
 
-         /// </summary>
 
-         /// <value>The URL.</value>
 
-         public string Url { get; set; }
 
-         /// <summary>
 
-         /// Gets or sets the query string.
 
-         /// </summary>
 
-         /// <value>The query string.</value>
 
-         public NameValueCollection QueryString { get; set; }
 
-         
 
-         /// <summary>
 
-         /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
 
-         /// </summary>
 
-         /// <param name="socket">The socket.</param>
 
-         /// <param name="remoteEndPoint">The remote end point.</param>
 
-         /// <param name="jsonSerializer">The json serializer.</param>
 
-         /// <param name="logger">The logger.</param>
 
-         /// <exception cref="System.ArgumentNullException">socket</exception>
 
-         public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger)
 
-         {
 
-             if (socket == null)
 
-             {
 
-                 throw new ArgumentNullException("socket");
 
-             }
 
-             if (string.IsNullOrEmpty(remoteEndPoint))
 
-             {
 
-                 throw new ArgumentNullException("remoteEndPoint");
 
-             }
 
-             if (jsonSerializer == null)
 
-             {
 
-                 throw new ArgumentNullException("jsonSerializer");
 
-             }
 
-             if (logger == null)
 
-             {
 
-                 throw new ArgumentNullException("logger");
 
-             }
 
-             Id = Guid.NewGuid();
 
-             _jsonSerializer = jsonSerializer;
 
-             _socket = socket;
 
-             _socket.OnReceiveBytes = OnReceiveInternal;
 
-             _socket.OnReceive = OnReceiveInternal;
 
-             RemoteEndPoint = remoteEndPoint;
 
-             _logger = logger;
 
-             socket.Closed += socket_Closed;
 
-         }
 
-         void socket_Closed(object sender, EventArgs e)
 
-         {
 
-             EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
 
-         }
 
-         /// <summary>
 
-         /// Called when [receive].
 
-         /// </summary>
 
-         /// <param name="bytes">The bytes.</param>
 
-         private void OnReceiveInternal(byte[] bytes)
 
-         {
 
-             LastActivityDate = DateTime.UtcNow;
 
-             if (OnReceive == null)
 
-             {
 
-                 return;
 
-             }
 
-             var charset = DetectCharset(bytes);
 
-             if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
 
-             {
 
-                 OnReceiveInternal(Encoding.UTF8.GetString(bytes));
 
-             }
 
-             else
 
-             {
 
-                 OnReceiveInternal(Encoding.ASCII.GetString(bytes));
 
-             }
 
-         }
 
-         private string DetectCharset(byte[] bytes)
 
-         {
 
-             try
 
-             {
 
-                 using (var ms = new MemoryStream(bytes))
 
-                 {
 
-                     var detector = new CharsetDetector();
 
-                     detector.Feed(ms);
 
-                     detector.DataEnd();
 
-                     var charset = detector.Charset;
 
-                     if (!string.IsNullOrWhiteSpace(charset))
 
-                     {
 
-                         //_logger.Debug("UniversalDetector detected charset {0}", charset);
 
-                     }
 
-                     return charset;
 
-                 }
 
-             }
 
-             catch (IOException ex)
 
-             {
 
-                 _logger.ErrorException("Error attempting to determine web socket message charset", ex);
 
-             }
 
-             return null;
 
-         }
 
-         private void OnReceiveInternal(string message)
 
-         {
 
-             LastActivityDate = DateTime.UtcNow;
 
-             if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
 
-             {
 
-                 // This info is useful sometimes but also clogs up the log
 
-                 //_logger.Error("Received web socket message that is not a json structure: " + message);
 
-                 return;
 
-             }
 
-             if (OnReceive == null)
 
-             {
 
-                 return;
 
-             }
 
-             try
 
-             {
 
-                 var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
 
-                 var info = new WebSocketMessageInfo
 
-                 {
 
-                     MessageType = stub.MessageType,
 
-                     Data = stub.Data == null ? null : stub.Data.ToString(),
 
-                     Connection = this
 
-                 };
 
-                 OnReceive(info);
 
-             }
 
-             catch (Exception ex)
 
-             {
 
-                 _logger.ErrorException("Error processing web socket message", ex);
 
-             }
 
-         }
 
-         
 
-         /// <summary>
 
-         /// Sends a message asynchronously.
 
-         /// </summary>
 
-         /// <typeparam name="T"></typeparam>
 
-         /// <param name="message">The message.</param>
 
-         /// <param name="cancellationToken">The cancellation token.</param>
 
-         /// <returns>Task.</returns>
 
-         /// <exception cref="System.ArgumentNullException">message</exception>
 
-         public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
 
-         {
 
-             if (message == null)
 
-             {
 
-                 throw new ArgumentNullException("message");
 
-             }
 
-             var json = _jsonSerializer.SerializeToString(message);
 
-             return SendAsync(json, cancellationToken);
 
-         }
 
-         /// <summary>
 
-         /// Sends a message asynchronously.
 
-         /// </summary>
 
-         /// <param name="buffer">The buffer.</param>
 
-         /// <param name="cancellationToken">The cancellation token.</param>
 
-         /// <returns>Task.</returns>
 
-         public async Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
 
-         {
 
-             if (buffer == null)
 
-             {
 
-                 throw new ArgumentNullException("buffer");
 
-             }
 
-             cancellationToken.ThrowIfCancellationRequested();
 
-             // Per msdn docs, attempting to send simultaneous messages will result in one failing.
 
-             // This should help us workaround that and ensure all messages get sent
 
-             await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
 
-             try
 
-             {
 
-                 await _socket.SendAsync(buffer, true, cancellationToken);
 
-             }
 
-             catch (OperationCanceledException)
 
-             {
 
-                 _logger.Info("WebSocket message to {0} was cancelled", RemoteEndPoint);
 
-                 throw;
 
-             }
 
-             catch (Exception ex)
 
-             {
 
-                 _logger.ErrorException("Error sending WebSocket message {0}", ex, RemoteEndPoint);
 
-                 throw;
 
-             }
 
-             finally
 
-             {
 
-                 _sendSemaphore.Release();
 
-             }
 
-         }
 
-         public async Task SendAsync(string text, CancellationToken cancellationToken)
 
-         {
 
-             if (string.IsNullOrWhiteSpace(text))
 
-             {
 
-                 throw new ArgumentNullException("text");
 
-             }
 
-             cancellationToken.ThrowIfCancellationRequested();
 
-             // Per msdn docs, attempting to send simultaneous messages will result in one failing.
 
-             // This should help us workaround that and ensure all messages get sent
 
-             await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
 
-             try
 
-             {
 
-                 await _socket.SendAsync(text, true, cancellationToken);
 
-             }
 
-             catch (OperationCanceledException)
 
-             {
 
-                 _logger.Info("WebSocket message to {0} was cancelled", RemoteEndPoint);
 
-                 throw;
 
-             }
 
-             catch (Exception ex)
 
-             {
 
-                 _logger.ErrorException("Error sending WebSocket message {0}", ex, RemoteEndPoint);
 
-                 throw;
 
-             }
 
-             finally
 
-             {
 
-                 _sendSemaphore.Release();
 
-             }
 
-         }
 
-         /// <summary>
 
-         /// Gets the state.
 
-         /// </summary>
 
-         /// <value>The state.</value>
 
-         public WebSocketState State
 
-         {
 
-             get { return _socket.State; }
 
-         }
 
-         /// <summary>
 
-         /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 
-         /// </summary>
 
-         public void Dispose()
 
-         {
 
-             Dispose(true);
 
-             GC.SuppressFinalize(this);
 
-         }
 
-         /// <summary>
 
-         /// Releases unmanaged and - optionally - managed resources.
 
-         /// </summary>
 
-         /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
 
-         protected virtual void Dispose(bool dispose)
 
-         {
 
-             if (dispose)
 
-             {
 
-                 _cancellationTokenSource.Dispose();
 
-                 _socket.Dispose();
 
-             }
 
-         }
 
-     }
 
- }
 
 
  |