ServerManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 IServerApplicationHost _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. /// Initializes a new instance of the <see cref="ServerManager" /> class.
  85. /// </summary>
  86. /// <param name="applicationHost">The application host.</param>
  87. /// <param name="jsonSerializer">The json serializer.</param>
  88. /// <param name="logger">The logger.</param>
  89. /// <param name="configurationManager">The configuration manager.</param>
  90. /// <exception cref="System.ArgumentNullException">applicationHost</exception>
  91. public ServerManager(IServerApplicationHost applicationHost, IJsonSerializer jsonSerializer, ILogger logger, IServerConfigurationManager configurationManager)
  92. {
  93. if (applicationHost == null)
  94. {
  95. throw new ArgumentNullException("applicationHost");
  96. }
  97. if (jsonSerializer == null)
  98. {
  99. throw new ArgumentNullException("jsonSerializer");
  100. }
  101. if (logger == null)
  102. {
  103. throw new ArgumentNullException("logger");
  104. }
  105. _logger = logger;
  106. _jsonSerializer = jsonSerializer;
  107. _applicationHost = applicationHost;
  108. ConfigurationManager = configurationManager;
  109. ConfigurationManager.ConfigurationUpdated += ConfigurationUpdated;
  110. }
  111. /// <summary>
  112. /// Starts this instance.
  113. /// </summary>
  114. public void Start()
  115. {
  116. ReloadHttpServer();
  117. if (!SupportsNativeWebSocket)
  118. {
  119. ReloadExternalWebSocketServer();
  120. }
  121. }
  122. /// <summary>
  123. /// Starts the external web socket server.
  124. /// </summary>
  125. private void ReloadExternalWebSocketServer()
  126. {
  127. DisposeExternalWebSocketServer();
  128. ExternalWebSocketServer = _applicationHost.Resolve<IWebSocketServer>();
  129. ExternalWebSocketServer.Start(ConfigurationManager.Configuration.LegacyWebSocketPortNumber);
  130. ExternalWebSocketServer.WebSocketConnected += HttpServer_WebSocketConnected;
  131. }
  132. /// <summary>
  133. /// Restarts the Http Server, or starts it if not currently running
  134. /// </summary>
  135. private void ReloadHttpServer()
  136. {
  137. // Only reload if the port has changed, so that we don't disconnect any active users
  138. if (HttpServer != null && HttpServer.UrlPrefix.Equals(_applicationHost.HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
  139. {
  140. return;
  141. }
  142. DisposeHttpServer();
  143. _logger.Info("Loading Http Server");
  144. try
  145. {
  146. HttpServer = _applicationHost.Resolve<IHttpServer>();
  147. HttpServer.EnableHttpRequestLogging = ConfigurationManager.Configuration.EnableHttpLevelLogging;
  148. HttpServer.Start(_applicationHost.HttpServerUrlPrefix);
  149. }
  150. catch (HttpListenerException ex)
  151. {
  152. _logger.ErrorException("Error starting Http Server", ex);
  153. throw;
  154. }
  155. HttpServer.WebSocketConnected += HttpServer_WebSocketConnected;
  156. }
  157. /// <summary>
  158. /// Handles the WebSocketConnected event of the HttpServer control.
  159. /// </summary>
  160. /// <param name="sender">The source of the event.</param>
  161. /// <param name="e">The <see cref="WebSocketConnectEventArgs" /> instance containing the event data.</param>
  162. void HttpServer_WebSocketConnected(object sender, WebSocketConnectEventArgs e)
  163. {
  164. var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger)
  165. {
  166. OnReceive = ProcessWebSocketMessageReceived
  167. };
  168. _webSocketConnections.Add(connection);
  169. }
  170. /// <summary>
  171. /// Processes the web socket message received.
  172. /// </summary>
  173. /// <param name="result">The result.</param>
  174. private async void ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  175. {
  176. var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
  177. {
  178. try
  179. {
  180. await i.ProcessMessage(result).ConfigureAwait(false);
  181. }
  182. catch (Exception ex)
  183. {
  184. _logger.ErrorException("{0} failed processing WebSocket message {1}", ex, i.GetType().Name, result.MessageType);
  185. }
  186. }));
  187. await Task.WhenAll(tasks).ConfigureAwait(false);
  188. }
  189. /// <summary>
  190. /// Sends a message to all clients currently connected via a web socket
  191. /// </summary>
  192. /// <typeparam name="T"></typeparam>
  193. /// <param name="messageType">Type of the message.</param>
  194. /// <param name="data">The data.</param>
  195. /// <returns>Task.</returns>
  196. public void SendWebSocketMessage<T>(string messageType, T data)
  197. {
  198. SendWebSocketMessage(messageType, () => data);
  199. }
  200. /// <summary>
  201. /// Sends a message to all clients currently connected via a web socket
  202. /// </summary>
  203. /// <typeparam name="T"></typeparam>
  204. /// <param name="messageType">Type of the message.</param>
  205. /// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
  206. public void SendWebSocketMessage<T>(string messageType, Func<T> dataFunction)
  207. {
  208. Task.Run(async () => await SendWebSocketMessageAsync(messageType, dataFunction, CancellationToken.None).ConfigureAwait(false));
  209. }
  210. /// <summary>
  211. /// Sends a message to all clients currently connected via a web socket
  212. /// </summary>
  213. /// <typeparam name="T"></typeparam>
  214. /// <param name="messageType">Type of the message.</param>
  215. /// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
  216. /// <param name="cancellationToken">The cancellation token.</param>
  217. /// <returns>Task.</returns>
  218. /// <exception cref="System.ArgumentNullException">messageType</exception>
  219. public Task SendWebSocketMessageAsync<T>(string messageType, Func<T> dataFunction, CancellationToken cancellationToken)
  220. {
  221. return SendWebSocketMessageAsync(messageType, dataFunction, _webSocketConnections, cancellationToken);
  222. }
  223. /// <summary>
  224. /// Sends the web socket message async.
  225. /// </summary>
  226. /// <typeparam name="T"></typeparam>
  227. /// <param name="messageType">Type of the message.</param>
  228. /// <param name="dataFunction">The data function.</param>
  229. /// <param name="connections">The connections.</param>
  230. /// <param name="cancellationToken">The cancellation token.</param>
  231. /// <returns>Task.</returns>
  232. /// <exception cref="System.ArgumentNullException">messageType
  233. /// or
  234. /// dataFunction
  235. /// or
  236. /// cancellationToken</exception>
  237. public async Task SendWebSocketMessageAsync<T>(string messageType, Func<T> dataFunction, IEnumerable<IWebSocketConnection> connections, CancellationToken cancellationToken)
  238. {
  239. if (string.IsNullOrEmpty(messageType))
  240. {
  241. throw new ArgumentNullException("messageType");
  242. }
  243. if (dataFunction == null)
  244. {
  245. throw new ArgumentNullException("dataFunction");
  246. }
  247. if (cancellationToken == null)
  248. {
  249. throw new ArgumentNullException("cancellationToken");
  250. }
  251. cancellationToken.ThrowIfCancellationRequested();
  252. var connectionsList = connections.Where(s => s.State == WebSocketState.Open).ToList();
  253. if (connectionsList.Count > 0)
  254. {
  255. _logger.Info("Sending web socket message {0}", messageType);
  256. var message = new WebSocketMessage<T> { MessageType = messageType, Data = dataFunction() };
  257. var bytes = _jsonSerializer.SerializeToBytes(message);
  258. var tasks = connectionsList.Select(s => Task.Run(() =>
  259. {
  260. try
  261. {
  262. s.SendAsync(bytes, cancellationToken);
  263. }
  264. catch (OperationCanceledException)
  265. {
  266. throw;
  267. }
  268. catch (Exception ex)
  269. {
  270. _logger.ErrorException("Error sending web socket message {0} to {1}", ex, messageType, s.RemoteEndPoint);
  271. }
  272. }));
  273. await Task.WhenAll(tasks).ConfigureAwait(false);
  274. }
  275. }
  276. /// <summary>
  277. /// Disposes the current HttpServer
  278. /// </summary>
  279. private void DisposeHttpServer()
  280. {
  281. foreach (var socket in _webSocketConnections)
  282. {
  283. // Dispose the connection
  284. socket.Dispose();
  285. }
  286. _webSocketConnections.Clear();
  287. if (HttpServer != null)
  288. {
  289. HttpServer.WebSocketConnected -= HttpServer_WebSocketConnected;
  290. HttpServer.Dispose();
  291. }
  292. DisposeExternalWebSocketServer();
  293. }
  294. /// <summary>
  295. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  296. /// </summary>
  297. public void Dispose()
  298. {
  299. Dispose(true);
  300. GC.SuppressFinalize(this);
  301. }
  302. /// <summary>
  303. /// Releases unmanaged and - optionally - managed resources.
  304. /// </summary>
  305. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  306. protected virtual void Dispose(bool dispose)
  307. {
  308. if (dispose)
  309. {
  310. DisposeHttpServer();
  311. }
  312. }
  313. /// <summary>
  314. /// Disposes the external web socket server.
  315. /// </summary>
  316. private void DisposeExternalWebSocketServer()
  317. {
  318. if (ExternalWebSocketServer != null)
  319. {
  320. _logger.Info("Disposing {0}", ExternalWebSocketServer.GetType().Name);
  321. ExternalWebSocketServer.Dispose();
  322. }
  323. }
  324. /// <summary>
  325. /// Handles the ConfigurationUpdated event of the _kernel control.
  326. /// </summary>
  327. /// <param name="sender">The source of the event.</param>
  328. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  329. /// <exception cref="System.NotImplementedException"></exception>
  330. void ConfigurationUpdated(object sender, EventArgs e)
  331. {
  332. HttpServer.EnableHttpRequestLogging = ConfigurationManager.Configuration.EnableHttpLevelLogging;
  333. }
  334. /// <summary>
  335. /// Adds the web socket listeners.
  336. /// </summary>
  337. /// <param name="listeners">The listeners.</param>
  338. public void AddWebSocketListeners(IEnumerable<IWebSocketListener> listeners)
  339. {
  340. _webSocketListeners.AddRange(listeners);
  341. }
  342. }
  343. }