ServerManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Net;
  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.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. /// The _logger
  46. /// </summary>
  47. private readonly ILogger _logger;
  48. /// <summary>
  49. /// The _application host
  50. /// </summary>
  51. private readonly IServerApplicationHost _applicationHost;
  52. /// <summary>
  53. /// Gets or sets the configuration manager.
  54. /// </summary>
  55. /// <value>The configuration manager.</value>
  56. private IServerConfigurationManager ConfigurationManager { get; set; }
  57. /// <summary>
  58. /// Gets the web socket listeners.
  59. /// </summary>
  60. /// <value>The web socket listeners.</value>
  61. private readonly List<IWebSocketListener> _webSocketListeners = new List<IWebSocketListener>();
  62. /// <summary>
  63. /// Initializes a new instance of the <see cref="ServerManager" /> class.
  64. /// </summary>
  65. /// <param name="applicationHost">The application host.</param>
  66. /// <param name="jsonSerializer">The json serializer.</param>
  67. /// <param name="logger">The logger.</param>
  68. /// <param name="configurationManager">The configuration manager.</param>
  69. /// <exception cref="System.ArgumentNullException">applicationHost</exception>
  70. public ServerManager(IServerApplicationHost applicationHost, IJsonSerializer jsonSerializer, ILogger logger, IServerConfigurationManager configurationManager)
  71. {
  72. if (applicationHost == null)
  73. {
  74. throw new ArgumentNullException("applicationHost");
  75. }
  76. if (jsonSerializer == null)
  77. {
  78. throw new ArgumentNullException("jsonSerializer");
  79. }
  80. if (logger == null)
  81. {
  82. throw new ArgumentNullException("logger");
  83. }
  84. _logger = logger;
  85. _jsonSerializer = jsonSerializer;
  86. _applicationHost = applicationHost;
  87. ConfigurationManager = configurationManager;
  88. }
  89. /// <summary>
  90. /// Starts this instance.
  91. /// </summary>
  92. public void Start(IEnumerable<string> urlPrefixes, string certificatePath)
  93. {
  94. ReloadHttpServer(urlPrefixes, certificatePath);
  95. }
  96. /// <summary>
  97. /// Restarts the Http Server, or starts it if not currently running
  98. /// </summary>
  99. private void ReloadHttpServer(IEnumerable<string> urlPrefixes, string certificatePath)
  100. {
  101. _logger.Info("Loading Http Server");
  102. try
  103. {
  104. HttpServer = _applicationHost.Resolve<IHttpServer>();
  105. HttpServer.StartServer(urlPrefixes, certificatePath);
  106. }
  107. catch (SocketException ex)
  108. {
  109. _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);
  110. throw;
  111. }
  112. catch (Exception ex)
  113. {
  114. _logger.ErrorException("Error starting Http Server", ex);
  115. throw;
  116. }
  117. HttpServer.WebSocketConnected += HttpServer_WebSocketConnected;
  118. }
  119. /// <summary>
  120. /// Handles the WebSocketConnected event of the HttpServer control.
  121. /// </summary>
  122. /// <param name="sender">The source of the event.</param>
  123. /// <param name="e">The <see cref="WebSocketConnectEventArgs" /> instance containing the event data.</param>
  124. void HttpServer_WebSocketConnected(object sender, WebSocketConnectEventArgs e)
  125. {
  126. var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger)
  127. {
  128. OnReceive = ProcessWebSocketMessageReceived
  129. };
  130. _webSocketConnections.Add(connection);
  131. }
  132. /// <summary>
  133. /// Processes the web socket message received.
  134. /// </summary>
  135. /// <param name="result">The result.</param>
  136. private async void ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  137. {
  138. //_logger.Debug("Websocket message received: {0}", result.MessageType);
  139. var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
  140. {
  141. try
  142. {
  143. await i.ProcessMessage(result).ConfigureAwait(false);
  144. }
  145. catch (Exception ex)
  146. {
  147. _logger.ErrorException("{0} failed processing WebSocket message {1}", ex, i.GetType().Name, result.MessageType ?? string.Empty);
  148. }
  149. }));
  150. await Task.WhenAll(tasks).ConfigureAwait(false);
  151. }
  152. /// <summary>
  153. /// Sends a message to all clients currently connected via a web socket
  154. /// </summary>
  155. /// <typeparam name="T"></typeparam>
  156. /// <param name="messageType">Type of the message.</param>
  157. /// <param name="data">The data.</param>
  158. /// <returns>Task.</returns>
  159. public void SendWebSocketMessage<T>(string messageType, T data)
  160. {
  161. SendWebSocketMessage(messageType, () => data);
  162. }
  163. /// <summary>
  164. /// Sends a message to all clients currently connected via a web socket
  165. /// </summary>
  166. /// <typeparam name="T"></typeparam>
  167. /// <param name="messageType">Type of the message.</param>
  168. /// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
  169. public void SendWebSocketMessage<T>(string messageType, Func<T> dataFunction)
  170. {
  171. SendWebSocketMessageAsync(messageType, dataFunction, CancellationToken.None);
  172. }
  173. /// <summary>
  174. /// Sends a message to all clients currently connected via a web socket
  175. /// </summary>
  176. /// <typeparam name="T"></typeparam>
  177. /// <param name="messageType">Type of the message.</param>
  178. /// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
  179. /// <param name="cancellationToken">The cancellation token.</param>
  180. /// <returns>Task.</returns>
  181. /// <exception cref="System.ArgumentNullException">messageType</exception>
  182. public Task SendWebSocketMessageAsync<T>(string messageType, Func<T> dataFunction, CancellationToken cancellationToken)
  183. {
  184. return SendWebSocketMessageAsync(messageType, dataFunction, _webSocketConnections, cancellationToken);
  185. }
  186. /// <summary>
  187. /// Sends the web socket message async.
  188. /// </summary>
  189. /// <typeparam name="T"></typeparam>
  190. /// <param name="messageType">Type of the message.</param>
  191. /// <param name="dataFunction">The data function.</param>
  192. /// <param name="connections">The connections.</param>
  193. /// <param name="cancellationToken">The cancellation token.</param>
  194. /// <returns>Task.</returns>
  195. /// <exception cref="System.ArgumentNullException">messageType
  196. /// or
  197. /// dataFunction
  198. /// or
  199. /// cancellationToken</exception>
  200. private async Task SendWebSocketMessageAsync<T>(string messageType, Func<T> dataFunction, IEnumerable<IWebSocketConnection> connections, CancellationToken cancellationToken)
  201. {
  202. if (string.IsNullOrEmpty(messageType))
  203. {
  204. throw new ArgumentNullException("messageType");
  205. }
  206. if (dataFunction == null)
  207. {
  208. throw new ArgumentNullException("dataFunction");
  209. }
  210. cancellationToken.ThrowIfCancellationRequested();
  211. var connectionsList = connections.Where(s => s.State == WebSocketState.Open).ToList();
  212. if (connectionsList.Count > 0)
  213. {
  214. _logger.Info("Sending web socket message {0}", messageType);
  215. var message = new WebSocketMessage<T> { MessageType = messageType, Data = dataFunction() };
  216. var json = _jsonSerializer.SerializeToString(message);
  217. var tasks = connectionsList.Select(s => Task.Run(() =>
  218. {
  219. try
  220. {
  221. s.SendAsync(json, cancellationToken);
  222. }
  223. catch (OperationCanceledException)
  224. {
  225. throw;
  226. }
  227. catch (Exception ex)
  228. {
  229. _logger.ErrorException("Error sending web socket message {0} to {1}", ex, messageType, s.RemoteEndPoint);
  230. }
  231. }, cancellationToken));
  232. await Task.WhenAll(tasks).ConfigureAwait(false);
  233. }
  234. }
  235. /// <summary>
  236. /// Disposes the current HttpServer
  237. /// </summary>
  238. private void DisposeHttpServer()
  239. {
  240. foreach (var socket in _webSocketConnections)
  241. {
  242. // Dispose the connection
  243. socket.Dispose();
  244. }
  245. _webSocketConnections.Clear();
  246. if (HttpServer != null)
  247. {
  248. HttpServer.WebSocketConnected -= HttpServer_WebSocketConnected;
  249. HttpServer.Dispose();
  250. }
  251. }
  252. /// <summary>
  253. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  254. /// </summary>
  255. public void Dispose()
  256. {
  257. Dispose(true);
  258. GC.SuppressFinalize(this);
  259. }
  260. /// <summary>
  261. /// Releases unmanaged and - optionally - managed resources.
  262. /// </summary>
  263. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  264. protected virtual void Dispose(bool dispose)
  265. {
  266. if (dispose)
  267. {
  268. DisposeHttpServer();
  269. }
  270. }
  271. /// <summary>
  272. /// Adds the web socket listeners.
  273. /// </summary>
  274. /// <param name="listeners">The listeners.</param>
  275. public void AddWebSocketListeners(IEnumerable<IWebSocketListener> listeners)
  276. {
  277. _webSocketListeners.AddRange(listeners);
  278. }
  279. }
  280. }