From 8ef442c2e8f39307f72bc98d6c79a9b5f09e6d72 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 3 Nov 2016 18:53:02 -0400 Subject: move classes --- .../ServerManager/ServerManager.cs | 353 --------------------- .../ServerManager/WebSocketConnection.cs | 292 ----------------- 2 files changed, 645 deletions(-) delete mode 100644 MediaBrowser.Server.Implementations/ServerManager/ServerManager.cs delete mode 100644 MediaBrowser.Server.Implementations/ServerManager/WebSocketConnection.cs (limited to 'MediaBrowser.Server.Implementations/ServerManager') diff --git a/MediaBrowser.Server.Implementations/ServerManager/ServerManager.cs b/MediaBrowser.Server.Implementations/ServerManager/ServerManager.cs deleted file mode 100644 index 4e706324f..000000000 --- a/MediaBrowser.Server.Implementations/ServerManager/ServerManager.cs +++ /dev/null @@ -1,353 +0,0 @@ -using MediaBrowser.Common.Events; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Net; -using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Net; -using MediaBrowser.Model.Serialization; -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Linq; -using System.Net.Sockets; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.IO; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.Services; - -namespace MediaBrowser.Server.Implementations.ServerManager -{ - /// - /// Manages the Http Server, Udp Server and WebSocket connections - /// - public class ServerManager : IServerManager - { - /// - /// Both the Ui and server will have a built-in HttpServer. - /// People will inevitably want remote control apps so it's needed in the Ui too. - /// - /// The HTTP server. - private IHttpServer HttpServer { get; set; } - - /// - /// Gets or sets the json serializer. - /// - /// The json serializer. - private readonly IJsonSerializer _jsonSerializer; - - /// - /// The web socket connections - /// - private readonly List _webSocketConnections = new List(); - /// - /// Gets the web socket connections. - /// - /// The web socket connections. - public IEnumerable WebSocketConnections - { - get { return _webSocketConnections; } - } - - public event EventHandler> WebSocketConnected; - - /// - /// The _logger - /// - private readonly ILogger _logger; - - /// - /// The _application host - /// - private readonly IServerApplicationHost _applicationHost; - - /// - /// Gets or sets the configuration manager. - /// - /// The configuration manager. - private IServerConfigurationManager ConfigurationManager { get; set; } - - /// - /// Gets the web socket listeners. - /// - /// The web socket listeners. - private readonly List _webSocketListeners = new List(); - - private bool _disposed; - private readonly IMemoryStreamProvider _memoryStreamProvider; - - /// - /// Initializes a new instance of the class. - /// - /// The application host. - /// The json serializer. - /// The logger. - /// The configuration manager. - /// applicationHost - public ServerManager(IServerApplicationHost applicationHost, IJsonSerializer jsonSerializer, ILogger logger, IServerConfigurationManager configurationManager, IMemoryStreamProvider memoryStreamProvider) - { - if (applicationHost == null) - { - throw new ArgumentNullException("applicationHost"); - } - if (jsonSerializer == null) - { - throw new ArgumentNullException("jsonSerializer"); - } - if (logger == null) - { - throw new ArgumentNullException("logger"); - } - - _logger = logger; - _jsonSerializer = jsonSerializer; - _applicationHost = applicationHost; - ConfigurationManager = configurationManager; - _memoryStreamProvider = memoryStreamProvider; - } - - /// - /// Starts this instance. - /// - public void Start(IEnumerable urlPrefixes, string certificatePath) - { - ReloadHttpServer(urlPrefixes, certificatePath); - } - - /// - /// Restarts the Http Server, or starts it if not currently running - /// - private void ReloadHttpServer(IEnumerable urlPrefixes, string certificatePath) - { - _logger.Info("Loading Http Server"); - - try - { - HttpServer = _applicationHost.Resolve(); - HttpServer.StartServer(urlPrefixes, certificatePath); - } - catch (SocketException ex) - { - _logger.ErrorException("The http server is unable to start due to a Socket error. This can occasionally happen when the operating system takes longer than usual to release the IP bindings from the previous session. This can take up to five minutes. Please try waiting or rebooting the system.", ex); - - throw; - } - catch (Exception ex) - { - _logger.ErrorException("Error starting Http Server", ex); - - throw; - } - - HttpServer.WebSocketConnected += HttpServer_WebSocketConnected; - } - - /// - /// Handles the WebSocketConnected event of the HttpServer control. - /// - /// The source of the event. - /// The instance containing the event data. - void HttpServer_WebSocketConnected(object sender, WebSocketConnectEventArgs e) - { - if (_disposed) - { - return; - } - - var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger, _memoryStreamProvider) - { - OnReceive = ProcessWebSocketMessageReceived, - Url = e.Url, - QueryString = e.QueryString ?? new QueryParamCollection() - }; - - _webSocketConnections.Add(connection); - - if (WebSocketConnected != null) - { - EventHelper.FireEventIfNotNull(WebSocketConnected, this, new GenericEventArgs (connection), _logger); - } - } - - /// - /// Processes the web socket message received. - /// - /// The result. - private async void ProcessWebSocketMessageReceived(WebSocketMessageInfo result) - { - if (_disposed) - { - return; - } - - //_logger.Debug("Websocket message received: {0}", result.MessageType); - - var tasks = _webSocketListeners.Select(i => Task.Run(async () => - { - try - { - await i.ProcessMessage(result).ConfigureAwait(false); - } - catch (Exception ex) - { - _logger.ErrorException("{0} failed processing WebSocket message {1}", ex, i.GetType().Name, result.MessageType ?? string.Empty); - } - })); - - await Task.WhenAll(tasks).ConfigureAwait(false); - } - - /// - /// Sends a message to all clients currently connected via a web socket - /// - /// - /// Type of the message. - /// The data. - /// Task. - public void SendWebSocketMessage(string messageType, T data) - { - SendWebSocketMessage(messageType, () => data); - } - - /// - /// Sends a message to all clients currently connected via a web socket - /// - /// - /// Type of the message. - /// The function that generates the data to send, if there are any connected clients - public void SendWebSocketMessage(string messageType, Func dataFunction) - { - SendWebSocketMessageAsync(messageType, dataFunction, CancellationToken.None); - } - - /// - /// Sends a message to all clients currently connected via a web socket - /// - /// - /// Type of the message. - /// The function that generates the data to send, if there are any connected clients - /// The cancellation token. - /// Task. - /// messageType - public Task SendWebSocketMessageAsync(string messageType, Func dataFunction, CancellationToken cancellationToken) - { - return SendWebSocketMessageAsync(messageType, dataFunction, _webSocketConnections, cancellationToken); - } - - /// - /// Sends the web socket message async. - /// - /// - /// Type of the message. - /// The data function. - /// The connections. - /// The cancellation token. - /// Task. - /// messageType - /// or - /// dataFunction - /// or - /// cancellationToken - private async Task SendWebSocketMessageAsync(string messageType, Func dataFunction, IEnumerable connections, CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(messageType)) - { - throw new ArgumentNullException("messageType"); - } - - if (dataFunction == null) - { - throw new ArgumentNullException("dataFunction"); - } - - if (_disposed) - { - throw new ObjectDisposedException(GetType().Name); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var connectionsList = connections.Where(s => s.State == WebSocketState.Open).ToList(); - - if (connectionsList.Count > 0) - { - _logger.Info("Sending web socket message {0}", messageType); - - var message = new WebSocketMessage { MessageType = messageType, Data = dataFunction() }; - var json = _jsonSerializer.SerializeToString(message); - - var tasks = connectionsList.Select(s => Task.Run(() => - { - try - { - s.SendAsync(json, cancellationToken); - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - _logger.ErrorException("Error sending web socket message {0} to {1}", ex, messageType, s.RemoteEndPoint); - } - - }, cancellationToken)); - - await Task.WhenAll(tasks).ConfigureAwait(false); - } - } - - /// - /// Disposes the current HttpServer - /// - private void DisposeHttpServer() - { - foreach (var socket in _webSocketConnections) - { - // Dispose the connection - socket.Dispose(); - } - - _webSocketConnections.Clear(); - - if (HttpServer != null) - { - HttpServer.WebSocketConnected -= HttpServer_WebSocketConnected; - HttpServer.Dispose(); - } - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() - { - _disposed = true; - - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool dispose) - { - if (dispose) - { - DisposeHttpServer(); - } - } - - /// - /// Adds the web socket listeners. - /// - /// The listeners. - public void AddWebSocketListeners(IEnumerable listeners) - { - _webSocketListeners.AddRange(listeners); - } - } -} diff --git a/MediaBrowser.Server.Implementations/ServerManager/WebSocketConnection.cs b/MediaBrowser.Server.Implementations/ServerManager/WebSocketConnection.cs deleted file mode 100644 index c1bd8ed6b..000000000 --- a/MediaBrowser.Server.Implementations/ServerManager/WebSocketConnection.cs +++ /dev/null @@ -1,292 +0,0 @@ -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 MediaBrowser.Common.IO; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.Services; -using UniversalDetector; - -namespace MediaBrowser.Server.Implementations.ServerManager -{ - /// - /// Class WebSocketConnection - /// - public class WebSocketConnection : IWebSocketConnection - { - public event EventHandler Closed; - - /// - /// The _socket - /// - private readonly IWebSocket _socket; - - /// - /// The _remote end point - /// - public string RemoteEndPoint { get; private set; } - - /// - /// The _cancellation token source - /// - private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); - - /// - /// The logger - /// - private readonly ILogger _logger; - - /// - /// The _json serializer - /// - private readonly IJsonSerializer _jsonSerializer; - - /// - /// Gets or sets the receive action. - /// - /// The receive action. - public Action OnReceive { get; set; } - - /// - /// Gets the last activity date. - /// - /// The last activity date. - public DateTime LastActivityDate { get; private set; } - - /// - /// Gets the id. - /// - /// The id. - public Guid Id { get; private set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string Url { get; set; } - /// - /// Gets or sets the query string. - /// - /// The query string. - public QueryParamCollection QueryString { get; set; } - private readonly IMemoryStreamProvider _memoryStreamProvider; - - /// - /// Initializes a new instance of the class. - /// - /// The socket. - /// The remote end point. - /// The json serializer. - /// The logger. - /// socket - public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger, IMemoryStreamProvider memoryStreamProvider) - { - 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; - _memoryStreamProvider = memoryStreamProvider; - - socket.Closed += socket_Closed; - } - - void socket_Closed(object sender, EventArgs e) - { - EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger); - } - - /// - /// Called when [receive]. - /// - /// The bytes. - 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 = _memoryStreamProvider.CreateNew(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)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage)); - - 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); - } - } - - /// - /// Sends a message asynchronously. - /// - /// - /// The message. - /// The cancellation token. - /// Task. - /// message - public Task SendAsync(WebSocketMessage message, CancellationToken cancellationToken) - { - if (message == null) - { - throw new ArgumentNullException("message"); - } - - var json = _jsonSerializer.SerializeToString(message); - - return SendAsync(json, cancellationToken); - } - - /// - /// Sends a message asynchronously. - /// - /// The buffer. - /// The cancellation token. - /// Task. - public Task SendAsync(byte[] buffer, CancellationToken cancellationToken) - { - if (buffer == null) - { - throw new ArgumentNullException("buffer"); - } - - cancellationToken.ThrowIfCancellationRequested(); - - return _socket.SendAsync(buffer, true, cancellationToken); - } - - public Task SendAsync(string text, CancellationToken cancellationToken) - { - if (string.IsNullOrWhiteSpace(text)) - { - throw new ArgumentNullException("text"); - } - - cancellationToken.ThrowIfCancellationRequested(); - - return _socket.SendAsync(text, true, cancellationToken); - } - - /// - /// Gets the state. - /// - /// The state. - public WebSocketState State - { - get { return _socket.State; } - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool dispose) - { - if (dispose) - { - _cancellationTokenSource.Dispose(); - _socket.Dispose(); - } - } - } -} -- cgit v1.2.3