jellyfin-server/MediaBrowser.Server.Implementations/ServerManager/ServerManager.cs

319 lines
12 KiB
C#
Raw Normal View History

2013-09-18 02:43:34 +00:00
using MediaBrowser.Common.Net;
2013-03-07 05:34:00 +00:00
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
2013-12-07 15:52:38 +00:00
using MediaBrowser.Controller.Net;
2013-02-21 21:39:53 +00:00
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Net;
2013-02-25 02:41:51 +00:00
using MediaBrowser.Model.Serialization;
2013-02-21 01:33:05 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
2013-09-18 02:43:34 +00:00
using System.Net.Sockets;
2013-02-21 01:33:05 +00:00
using System.Threading;
using System.Threading.Tasks;
2013-03-07 05:34:00 +00:00
namespace MediaBrowser.Server.Implementations.ServerManager
2013-02-21 01:33:05 +00:00
{
/// <summary>
/// Manages the Http Server, Udp Server and WebSocket connections
/// </summary>
2013-03-27 22:13:46 +00:00
public class ServerManager : IServerManager
2013-02-21 01:33:05 +00:00
{
/// <summary>
/// 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.
/// </summary>
/// <value>The HTTP server.</value>
private IHttpServer HttpServer { get; set; }
2013-02-21 01:33:05 +00:00
2013-02-24 21:53:54 +00:00
/// <summary>
/// Gets or sets the json serializer.
/// </summary>
/// <value>The json serializer.</value>
2013-02-25 00:13:45 +00:00
private readonly IJsonSerializer _jsonSerializer;
2013-02-21 01:33:05 +00:00
/// <summary>
/// The web socket connections
/// </summary>
private readonly List<IWebSocketConnection> _webSocketConnections = new List<IWebSocketConnection>();
/// <summary>
/// Gets the web socket connections.
/// </summary>
/// <value>The web socket connections.</value>
public IEnumerable<IWebSocketConnection> WebSocketConnections
{
get { return _webSocketConnections; }
}
2013-02-21 01:33:05 +00:00
2013-02-21 21:39:53 +00:00
/// <summary>
/// The _logger
/// </summary>
private readonly ILogger _logger;
2013-02-22 04:23:06 +00:00
/// <summary>
/// The _application host
/// </summary>
2013-06-03 18:15:35 +00:00
private readonly IServerApplicationHost _applicationHost;
2013-02-21 01:33:05 +00:00
2013-03-04 05:43:06 +00:00
/// <summary>
/// Gets or sets the configuration manager.
/// </summary>
/// <value>The configuration manager.</value>
2013-03-07 05:34:00 +00:00
private IServerConfigurationManager ConfigurationManager { get; set; }
2013-03-04 05:43:06 +00:00
2013-02-27 16:46:48 +00:00
/// <summary>
/// Gets the web socket listeners.
/// </summary>
/// <value>The web socket listeners.</value>
2013-03-04 05:43:06 +00:00
private readonly List<IWebSocketListener> _webSocketListeners = new List<IWebSocketListener>();
2013-02-27 16:46:48 +00:00
2013-02-21 01:33:05 +00:00
/// <summary>
/// Initializes a new instance of the <see cref="ServerManager" /> class.
2013-02-21 01:33:05 +00:00
/// </summary>
2013-02-22 04:23:06 +00:00
/// <param name="applicationHost">The application host.</param>
2013-02-24 21:53:54 +00:00
/// <param name="jsonSerializer">The json serializer.</param>
2013-02-21 21:39:53 +00:00
/// <param name="logger">The logger.</param>
2013-03-04 05:43:06 +00:00
/// <param name="configurationManager">The configuration manager.</param>
2013-02-24 21:53:54 +00:00
/// <exception cref="System.ArgumentNullException">applicationHost</exception>
2013-06-03 18:15:35 +00:00
public ServerManager(IServerApplicationHost applicationHost, IJsonSerializer jsonSerializer, ILogger logger, IServerConfigurationManager configurationManager)
2013-02-21 01:33:05 +00:00
{
if (applicationHost == null)
{
throw new ArgumentNullException("applicationHost");
}
2013-02-24 21:53:54 +00:00
if (jsonSerializer == null)
{
throw new ArgumentNullException("jsonSerializer");
}
if (logger == null)
{
throw new ArgumentNullException("logger");
}
2013-02-21 21:39:53 +00:00
_logger = logger;
2013-02-24 21:53:54 +00:00
_jsonSerializer = jsonSerializer;
2013-02-22 04:23:06 +00:00
_applicationHost = applicationHost;
2013-03-04 05:43:06 +00:00
ConfigurationManager = configurationManager;
}
2013-02-21 21:39:53 +00:00
/// <summary>
/// Starts this instance.
/// </summary>
public void Start(IEnumerable<string> urlPrefixes, string certificatePath)
{
ReloadHttpServer(urlPrefixes, certificatePath);
}
2013-02-21 01:33:05 +00:00
/// <summary>
/// Restarts the Http Server, or starts it if not currently running
/// </summary>
private void ReloadHttpServer(IEnumerable<string> urlPrefixes, string certificatePath)
2013-02-21 01:33:05 +00:00
{
2013-02-21 21:39:53 +00:00
_logger.Info("Loading Http Server");
2013-02-21 01:33:05 +00:00
try
{
HttpServer = _applicationHost.Resolve<IHttpServer>();
HttpServer.StartServer(urlPrefixes, certificatePath);
2013-02-21 01:33:05 +00:00
}
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;
}
2014-02-19 05:21:03 +00:00
catch (Exception ex)
2013-02-21 01:33:05 +00:00
{
2013-02-21 21:39:53 +00:00
_logger.ErrorException("Error starting Http Server", ex);
2013-02-21 01:33:05 +00:00
throw;
}
HttpServer.WebSocketConnected += HttpServer_WebSocketConnected;
}
/// <summary>
/// Handles the WebSocketConnected event of the HttpServer control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="WebSocketConnectEventArgs" /> instance containing the event data.</param>
void HttpServer_WebSocketConnected(object sender, WebSocketConnectEventArgs e)
{
var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger)
{
OnReceive = ProcessWebSocketMessageReceived
};
2013-02-21 01:33:05 +00:00
_webSocketConnections.Add(connection);
}
/// <summary>
/// Processes the web socket message received.
/// </summary>
/// <param name="result">The result.</param>
private async void ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
{
2014-08-10 22:13:17 +00:00
//_logger.Debug("Websocket message received: {0}", result.MessageType);
2013-03-04 05:43:06 +00:00
var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
2013-02-21 01:33:05 +00:00
{
try
{
await i.ProcessMessage(result).ConfigureAwait(false);
}
catch (Exception ex)
{
2014-02-11 04:55:01 +00:00
_logger.ErrorException("{0} failed processing WebSocket message {1}", ex, i.GetType().Name, result.MessageType ?? string.Empty);
2013-02-21 01:33:05 +00:00
}
}));
await Task.WhenAll(tasks).ConfigureAwait(false);
}
/// <summary>
/// Sends a message to all clients currently connected via a web socket
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="messageType">Type of the message.</param>
/// <param name="data">The data.</param>
/// <returns>Task.</returns>
public void SendWebSocketMessage<T>(string messageType, T data)
{
SendWebSocketMessage(messageType, () => data);
}
/// <summary>
/// Sends a message to all clients currently connected via a web socket
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="messageType">Type of the message.</param>
/// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
public void SendWebSocketMessage<T>(string messageType, Func<T> dataFunction)
{
2013-12-30 02:41:22 +00:00
SendWebSocketMessageAsync(messageType, dataFunction, CancellationToken.None);
2013-02-21 01:33:05 +00:00
}
/// <summary>
/// Sends a message to all clients currently connected via a web socket
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="messageType">Type of the message.</param>
/// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">messageType</exception>
public Task SendWebSocketMessageAsync<T>(string messageType, Func<T> dataFunction, CancellationToken cancellationToken)
{
return SendWebSocketMessageAsync(messageType, dataFunction, _webSocketConnections, cancellationToken);
}
/// <summary>
/// Sends the web socket message async.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="messageType">Type of the message.</param>
/// <param name="dataFunction">The data function.</param>
/// <param name="connections">The connections.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">messageType
/// or
/// dataFunction
/// or
/// cancellationToken</exception>
2013-10-03 01:22:50 +00:00
private async Task SendWebSocketMessageAsync<T>(string messageType, Func<T> dataFunction, IEnumerable<IWebSocketConnection> connections, CancellationToken cancellationToken)
2013-02-21 01:33:05 +00:00
{
if (string.IsNullOrEmpty(messageType))
{
throw new ArgumentNullException("messageType");
}
if (dataFunction == null)
{
throw new ArgumentNullException("dataFunction");
}
cancellationToken.ThrowIfCancellationRequested();
var connectionsList = connections.Where(s => s.State == WebSocketState.Open).ToList();
2013-02-21 01:33:05 +00:00
if (connectionsList.Count > 0)
2013-02-21 01:33:05 +00:00
{
2013-02-21 21:39:53 +00:00
_logger.Info("Sending web socket message {0}", messageType);
2013-02-21 01:33:05 +00:00
var message = new WebSocketMessage<T> { MessageType = messageType, Data = dataFunction() };
2014-07-20 04:46:29 +00:00
var json = _jsonSerializer.SerializeToString(message);
2013-02-21 01:33:05 +00:00
var tasks = connectionsList.Select(s => Task.Run(() =>
2013-02-21 01:33:05 +00:00
{
try
{
2014-07-20 04:46:29 +00:00
s.SendAsync(json, cancellationToken);
2013-02-21 01:33:05 +00:00
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
2013-02-21 21:39:53 +00:00
_logger.ErrorException("Error sending web socket message {0} to {1}", ex, messageType, s.RemoteEndPoint);
2013-02-21 01:33:05 +00:00
}
2014-07-20 04:46:29 +00:00
}, cancellationToken));
2013-02-21 01:33:05 +00:00
await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
/// <summary>
/// Disposes the current HttpServer
/// </summary>
private void DisposeHttpServer()
{
foreach (var socket in _webSocketConnections)
{
// Dispose the connection
socket.Dispose();
}
_webSocketConnections.Clear();
if (HttpServer != null)
{
HttpServer.WebSocketConnected -= HttpServer_WebSocketConnected;
HttpServer.Dispose();
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
2013-02-21 01:33:05 +00:00
/// <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)
2013-02-21 01:33:05 +00:00
{
if (dispose)
{
DisposeHttpServer();
}
}
2013-02-27 16:46:48 +00:00
/// <summary>
/// Adds the web socket listeners.
/// </summary>
/// <param name="listeners">The listeners.</param>
public void AddWebSocketListeners(IEnumerable<IWebSocketListener> listeners)
{
2013-03-04 05:43:06 +00:00
_webSocketListeners.AddRange(listeners);
2013-02-27 16:46:48 +00:00
}
2013-02-21 01:33:05 +00:00
}
}