ServerManager.cs 14 KB

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