ServerManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Net;
  7. using MediaBrowser.Model.Serialization;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Server.Implementations.ServerManager
  15. {
  16. /// <summary>
  17. /// Manages the Http Server, Udp Server and WebSocket connections
  18. /// </summary>
  19. public class ServerManager : IServerManager
  20. {
  21. /// <summary>
  22. /// Both the Ui and server will have a built-in HttpServer.
  23. /// People will inevitably want remote control apps so it's needed in the Ui too.
  24. /// </summary>
  25. /// <value>The HTTP server.</value>
  26. private IHttpServer HttpServer { get; set; }
  27. /// <summary>
  28. /// Gets or sets the json serializer.
  29. /// </summary>
  30. /// <value>The json serializer.</value>
  31. private readonly IJsonSerializer _jsonSerializer;
  32. /// <summary>
  33. /// The web socket connections
  34. /// </summary>
  35. private readonly List<IWebSocketConnection> _webSocketConnections = new List<IWebSocketConnection>();
  36. /// <summary>
  37. /// Gets the web socket connections.
  38. /// </summary>
  39. /// <value>The web socket connections.</value>
  40. public IEnumerable<IWebSocketConnection> WebSocketConnections
  41. {
  42. get { return _webSocketConnections; }
  43. }
  44. /// <summary>
  45. /// Gets or sets the external web socket server.
  46. /// </summary>
  47. /// <value>The external web socket server.</value>
  48. private IWebSocketServer ExternalWebSocketServer { get; set; }
  49. /// <summary>
  50. /// The _logger
  51. /// </summary>
  52. private readonly ILogger _logger;
  53. /// <summary>
  54. /// The _application host
  55. /// </summary>
  56. private readonly IApplicationHost _applicationHost;
  57. /// <summary>
  58. /// Gets or sets the configuration manager.
  59. /// </summary>
  60. /// <value>The configuration manager.</value>
  61. private IServerConfigurationManager ConfigurationManager { get; set; }
  62. /// <summary>
  63. /// Gets a value indicating whether [supports web socket].
  64. /// </summary>
  65. /// <value><c>true</c> if [supports web socket]; otherwise, <c>false</c>.</value>
  66. public bool SupportsNativeWebSocket
  67. {
  68. get { return HttpServer != null && HttpServer.SupportsWebSockets; }
  69. }
  70. /// <summary>
  71. /// Gets the web socket port number.
  72. /// </summary>
  73. /// <value>The web socket port number.</value>
  74. public int WebSocketPortNumber
  75. {
  76. get { return SupportsNativeWebSocket ? ConfigurationManager.Configuration.HttpServerPortNumber : ConfigurationManager.Configuration.LegacyWebSocketPortNumber; }
  77. }
  78. /// <summary>
  79. /// Gets the web socket listeners.
  80. /// </summary>
  81. /// <value>The web socket listeners.</value>
  82. private readonly List<IWebSocketListener> _webSocketListeners = new List<IWebSocketListener>();
  83. /// <summary>
  84. /// The _kernel
  85. /// </summary>
  86. private readonly Kernel _kernel;
  87. /// <summary>
  88. /// Initializes a new instance of the <see cref="ServerManager" /> class.
  89. /// </summary>
  90. /// <param name="applicationHost">The application host.</param>
  91. /// <param name="jsonSerializer">The json serializer.</param>
  92. /// <param name="logger">The logger.</param>
  93. /// <param name="configurationManager">The configuration manager.</param>
  94. /// <param name="kernel">The kernel.</param>
  95. /// <exception cref="System.ArgumentNullException">applicationHost</exception>
  96. public ServerManager(IApplicationHost applicationHost, IJsonSerializer jsonSerializer, ILogger logger, IServerConfigurationManager configurationManager, Kernel kernel)
  97. {
  98. if (applicationHost == null)
  99. {
  100. throw new ArgumentNullException("applicationHost");
  101. }
  102. if (jsonSerializer == null)
  103. {
  104. throw new ArgumentNullException("jsonSerializer");
  105. }
  106. if (logger == null)
  107. {
  108. throw new ArgumentNullException("logger");
  109. }
  110. _logger = logger;
  111. _jsonSerializer = jsonSerializer;
  112. _applicationHost = applicationHost;
  113. ConfigurationManager = configurationManager;
  114. _kernel = kernel;
  115. ConfigurationManager.ConfigurationUpdated += ConfigurationUpdated;
  116. }
  117. /// <summary>
  118. /// Starts this instance.
  119. /// </summary>
  120. public void Start()
  121. {
  122. ReloadHttpServer();
  123. if (!SupportsNativeWebSocket)
  124. {
  125. ReloadExternalWebSocketServer();
  126. }
  127. }
  128. /// <summary>
  129. /// Starts the external web socket server.
  130. /// </summary>
  131. private void ReloadExternalWebSocketServer()
  132. {
  133. DisposeExternalWebSocketServer();
  134. ExternalWebSocketServer = _applicationHost.Resolve<IWebSocketServer>();
  135. ExternalWebSocketServer.Start(ConfigurationManager.Configuration.LegacyWebSocketPortNumber);
  136. ExternalWebSocketServer.WebSocketConnected += HttpServer_WebSocketConnected;
  137. }
  138. /// <summary>
  139. /// Restarts the Http Server, or starts it if not currently running
  140. /// </summary>
  141. private void ReloadHttpServer()
  142. {
  143. // Only reload if the port has changed, so that we don't disconnect any active users
  144. if (HttpServer != null && HttpServer.UrlPrefix.Equals(_kernel.HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
  145. {
  146. return;
  147. }
  148. DisposeHttpServer();
  149. _logger.Info("Loading Http Server");
  150. try
  151. {
  152. HttpServer = _applicationHost.Resolve<IHttpServer>();
  153. HttpServer.EnableHttpRequestLogging = ConfigurationManager.Configuration.EnableHttpLevelLogging;
  154. HttpServer.Start(_kernel.HttpServerUrlPrefix);
  155. }
  156. catch (HttpListenerException ex)
  157. {
  158. _logger.ErrorException("Error starting Http Server", ex);
  159. throw;
  160. }
  161. HttpServer.WebSocketConnected += HttpServer_WebSocketConnected;
  162. }
  163. /// <summary>
  164. /// Handles the WebSocketConnected event of the HttpServer control.
  165. /// </summary>
  166. /// <param name="sender">The source of the event.</param>
  167. /// <param name="e">The <see cref="WebSocketConnectEventArgs" /> instance containing the event data.</param>
  168. void HttpServer_WebSocketConnected(object sender, WebSocketConnectEventArgs e)
  169. {
  170. var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger) { OnReceive = ProcessWebSocketMessageReceived };
  171. _webSocketConnections.Add(connection);
  172. }
  173. /// <summary>
  174. /// Processes the web socket message received.
  175. /// </summary>
  176. /// <param name="result">The result.</param>
  177. private async void ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  178. {
  179. var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
  180. {
  181. try
  182. {
  183. await i.ProcessMessage(result).ConfigureAwait(false);
  184. }
  185. catch (Exception ex)
  186. {
  187. _logger.ErrorException("{0} failed processing WebSocket message {1}", ex, i.GetType().Name, result.MessageType);
  188. }
  189. }));
  190. await Task.WhenAll(tasks).ConfigureAwait(false);
  191. }
  192. /// <summary>
  193. /// Sends a message to all clients currently connected via a web socket
  194. /// </summary>
  195. /// <typeparam name="T"></typeparam>
  196. /// <param name="messageType">Type of the message.</param>
  197. /// <param name="data">The data.</param>
  198. /// <returns>Task.</returns>
  199. public void SendWebSocketMessage<T>(string messageType, T data)
  200. {
  201. SendWebSocketMessage(messageType, () => data);
  202. }
  203. /// <summary>
  204. /// Sends a message to all clients currently connected via a web socket
  205. /// </summary>
  206. /// <typeparam name="T"></typeparam>
  207. /// <param name="messageType">Type of the message.</param>
  208. /// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
  209. public void SendWebSocketMessage<T>(string messageType, Func<T> dataFunction)
  210. {
  211. Task.Run(async () => await SendWebSocketMessageAsync(messageType, dataFunction, CancellationToken.None).ConfigureAwait(false));
  212. }
  213. /// <summary>
  214. /// Sends a message to all clients currently connected via a web socket
  215. /// </summary>
  216. /// <typeparam name="T"></typeparam>
  217. /// <param name="messageType">Type of the message.</param>
  218. /// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
  219. /// <param name="cancellationToken">The cancellation token.</param>
  220. /// <returns>Task.</returns>
  221. /// <exception cref="System.ArgumentNullException">messageType</exception>
  222. public Task SendWebSocketMessageAsync<T>(string messageType, Func<T> dataFunction, CancellationToken cancellationToken)
  223. {
  224. return SendWebSocketMessageAsync(messageType, dataFunction, _webSocketConnections, cancellationToken);
  225. }
  226. /// <summary>
  227. /// Sends the web socket message async.
  228. /// </summary>
  229. /// <typeparam name="T"></typeparam>
  230. /// <param name="messageType">Type of the message.</param>
  231. /// <param name="dataFunction">The data function.</param>
  232. /// <param name="connections">The connections.</param>
  233. /// <param name="cancellationToken">The cancellation token.</param>
  234. /// <returns>Task.</returns>
  235. /// <exception cref="System.ArgumentNullException">messageType
  236. /// or
  237. /// dataFunction
  238. /// or
  239. /// cancellationToken</exception>
  240. public async Task SendWebSocketMessageAsync<T>(string messageType, Func<T> dataFunction, IEnumerable<IWebSocketConnection> connections, CancellationToken cancellationToken)
  241. {
  242. if (string.IsNullOrEmpty(messageType))
  243. {
  244. throw new ArgumentNullException("messageType");
  245. }
  246. if (dataFunction == null)
  247. {
  248. throw new ArgumentNullException("dataFunction");
  249. }
  250. if (cancellationToken == null)
  251. {
  252. throw new ArgumentNullException("cancellationToken");
  253. }
  254. cancellationToken.ThrowIfCancellationRequested();
  255. var connectionsList = connections.Where(s => s.State == WebSocketState.Open).ToList();
  256. if (connectionsList.Count > 0)
  257. {
  258. _logger.Info("Sending web socket message {0}", messageType);
  259. var message = new WebSocketMessage<T> { MessageType = messageType, Data = dataFunction() };
  260. var bytes = _jsonSerializer.SerializeToBytes(message);
  261. var tasks = connectionsList.Select(s => Task.Run(() =>
  262. {
  263. try
  264. {
  265. s.SendAsync(bytes, cancellationToken);
  266. }
  267. catch (OperationCanceledException)
  268. {
  269. throw;
  270. }
  271. catch (Exception ex)
  272. {
  273. _logger.ErrorException("Error sending web socket message {0} to {1}", ex, messageType, s.RemoteEndPoint);
  274. }
  275. }));
  276. await Task.WhenAll(tasks).ConfigureAwait(false);
  277. }
  278. }
  279. /// <summary>
  280. /// Disposes the current HttpServer
  281. /// </summary>
  282. private void DisposeHttpServer()
  283. {
  284. foreach (var socket in _webSocketConnections)
  285. {
  286. // Dispose the connection
  287. socket.Dispose();
  288. }
  289. _webSocketConnections.Clear();
  290. if (HttpServer != null)
  291. {
  292. HttpServer.WebSocketConnected -= HttpServer_WebSocketConnected;
  293. HttpServer.Dispose();
  294. }
  295. DisposeExternalWebSocketServer();
  296. }
  297. /// <summary>
  298. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  299. /// </summary>
  300. public void Dispose()
  301. {
  302. Dispose(true);
  303. GC.SuppressFinalize(this);
  304. }
  305. /// <summary>
  306. /// Releases unmanaged and - optionally - managed resources.
  307. /// </summary>
  308. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  309. protected virtual void Dispose(bool dispose)
  310. {
  311. if (dispose)
  312. {
  313. DisposeHttpServer();
  314. }
  315. }
  316. /// <summary>
  317. /// Disposes the external web socket server.
  318. /// </summary>
  319. private void DisposeExternalWebSocketServer()
  320. {
  321. if (ExternalWebSocketServer != null)
  322. {
  323. _logger.Info("Disposing {0}", ExternalWebSocketServer.GetType().Name);
  324. ExternalWebSocketServer.Dispose();
  325. }
  326. }
  327. /// <summary>
  328. /// Handles the ConfigurationUpdated event of the _kernel control.
  329. /// </summary>
  330. /// <param name="sender">The source of the event.</param>
  331. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  332. /// <exception cref="System.NotImplementedException"></exception>
  333. void ConfigurationUpdated(object sender, EventArgs e)
  334. {
  335. HttpServer.EnableHttpRequestLogging = ConfigurationManager.Configuration.EnableHttpLevelLogging;
  336. }
  337. /// <summary>
  338. /// Adds the web socket listeners.
  339. /// </summary>
  340. /// <param name="listeners">The listeners.</param>
  341. public void AddWebSocketListeners(IEnumerable<IWebSocketListener> listeners)
  342. {
  343. _webSocketListeners.AddRange(listeners);
  344. }
  345. }
  346. }