ServerManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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) { OnReceive = ProcessWebSocketMessageReceived };
  165. _webSocketConnections.Add(connection);
  166. }
  167. /// <summary>
  168. /// Processes the web socket message received.
  169. /// </summary>
  170. /// <param name="result">The result.</param>
  171. private async void ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  172. {
  173. var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
  174. {
  175. try
  176. {
  177. await i.ProcessMessage(result).ConfigureAwait(false);
  178. }
  179. catch (Exception ex)
  180. {
  181. _logger.ErrorException("{0} failed processing WebSocket message {1}", ex, i.GetType().Name, result.MessageType);
  182. }
  183. }));
  184. await Task.WhenAll(tasks).ConfigureAwait(false);
  185. }
  186. /// <summary>
  187. /// Sends a message to all clients currently connected via a web socket
  188. /// </summary>
  189. /// <typeparam name="T"></typeparam>
  190. /// <param name="messageType">Type of the message.</param>
  191. /// <param name="data">The data.</param>
  192. /// <returns>Task.</returns>
  193. public void SendWebSocketMessage<T>(string messageType, T data)
  194. {
  195. SendWebSocketMessage(messageType, () => data);
  196. }
  197. /// <summary>
  198. /// Sends a message to all clients currently connected via a web socket
  199. /// </summary>
  200. /// <typeparam name="T"></typeparam>
  201. /// <param name="messageType">Type of the message.</param>
  202. /// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
  203. public void SendWebSocketMessage<T>(string messageType, Func<T> dataFunction)
  204. {
  205. Task.Run(async () => await SendWebSocketMessageAsync(messageType, dataFunction, CancellationToken.None).ConfigureAwait(false));
  206. }
  207. /// <summary>
  208. /// Sends a message to all clients currently connected via a web socket
  209. /// </summary>
  210. /// <typeparam name="T"></typeparam>
  211. /// <param name="messageType">Type of the message.</param>
  212. /// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
  213. /// <param name="cancellationToken">The cancellation token.</param>
  214. /// <returns>Task.</returns>
  215. /// <exception cref="System.ArgumentNullException">messageType</exception>
  216. public Task SendWebSocketMessageAsync<T>(string messageType, Func<T> dataFunction, CancellationToken cancellationToken)
  217. {
  218. return SendWebSocketMessageAsync(messageType, dataFunction, _webSocketConnections, cancellationToken);
  219. }
  220. /// <summary>
  221. /// Sends the web socket message async.
  222. /// </summary>
  223. /// <typeparam name="T"></typeparam>
  224. /// <param name="messageType">Type of the message.</param>
  225. /// <param name="dataFunction">The data function.</param>
  226. /// <param name="connections">The connections.</param>
  227. /// <param name="cancellationToken">The cancellation token.</param>
  228. /// <returns>Task.</returns>
  229. /// <exception cref="System.ArgumentNullException">messageType
  230. /// or
  231. /// dataFunction
  232. /// or
  233. /// cancellationToken</exception>
  234. public async Task SendWebSocketMessageAsync<T>(string messageType, Func<T> dataFunction, IEnumerable<IWebSocketConnection> connections, CancellationToken cancellationToken)
  235. {
  236. if (string.IsNullOrEmpty(messageType))
  237. {
  238. throw new ArgumentNullException("messageType");
  239. }
  240. if (dataFunction == null)
  241. {
  242. throw new ArgumentNullException("dataFunction");
  243. }
  244. if (cancellationToken == null)
  245. {
  246. throw new ArgumentNullException("cancellationToken");
  247. }
  248. cancellationToken.ThrowIfCancellationRequested();
  249. var connectionsList = connections.Where(s => s.State == WebSocketState.Open).ToList();
  250. if (connectionsList.Count > 0)
  251. {
  252. _logger.Info("Sending web socket message {0}", messageType);
  253. var message = new WebSocketMessage<T> { MessageType = messageType, Data = dataFunction() };
  254. var bytes = _jsonSerializer.SerializeToBytes(message);
  255. var tasks = connectionsList.Select(s => Task.Run(() =>
  256. {
  257. try
  258. {
  259. s.SendAsync(bytes, cancellationToken);
  260. }
  261. catch (OperationCanceledException)
  262. {
  263. throw;
  264. }
  265. catch (Exception ex)
  266. {
  267. _logger.ErrorException("Error sending web socket message {0} to {1}", ex, messageType, s.RemoteEndPoint);
  268. }
  269. }));
  270. await Task.WhenAll(tasks).ConfigureAwait(false);
  271. }
  272. }
  273. /// <summary>
  274. /// Disposes the current HttpServer
  275. /// </summary>
  276. private void DisposeHttpServer()
  277. {
  278. foreach (var socket in _webSocketConnections)
  279. {
  280. // Dispose the connection
  281. socket.Dispose();
  282. }
  283. _webSocketConnections.Clear();
  284. if (HttpServer != null)
  285. {
  286. HttpServer.WebSocketConnected -= HttpServer_WebSocketConnected;
  287. HttpServer.Dispose();
  288. }
  289. DisposeExternalWebSocketServer();
  290. }
  291. /// <summary>
  292. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  293. /// </summary>
  294. public void Dispose()
  295. {
  296. Dispose(true);
  297. GC.SuppressFinalize(this);
  298. }
  299. /// <summary>
  300. /// Releases unmanaged and - optionally - managed resources.
  301. /// </summary>
  302. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  303. protected virtual void Dispose(bool dispose)
  304. {
  305. if (dispose)
  306. {
  307. DisposeHttpServer();
  308. }
  309. }
  310. /// <summary>
  311. /// Disposes the external web socket server.
  312. /// </summary>
  313. private void DisposeExternalWebSocketServer()
  314. {
  315. if (ExternalWebSocketServer != null)
  316. {
  317. _logger.Info("Disposing {0}", ExternalWebSocketServer.GetType().Name);
  318. ExternalWebSocketServer.Dispose();
  319. }
  320. }
  321. /// <summary>
  322. /// Handles the ConfigurationUpdated event of the _kernel control.
  323. /// </summary>
  324. /// <param name="sender">The source of the event.</param>
  325. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  326. /// <exception cref="System.NotImplementedException"></exception>
  327. void ConfigurationUpdated(object sender, EventArgs e)
  328. {
  329. HttpServer.EnableHttpRequestLogging = ConfigurationManager.Configuration.EnableHttpLevelLogging;
  330. }
  331. /// <summary>
  332. /// Adds the web socket listeners.
  333. /// </summary>
  334. /// <param name="listeners">The listeners.</param>
  335. public void AddWebSocketListeners(IEnumerable<IWebSocketListener> listeners)
  336. {
  337. _webSocketListeners.AddRange(listeners);
  338. }
  339. }
  340. }