ServerManager.cs 13 KB

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