ApplicationHost.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. using MediaBrowser.Api;
  2. using MediaBrowser.Common;
  3. using MediaBrowser.Common.Configuration;
  4. using MediaBrowser.Common.Constants;
  5. using MediaBrowser.Common.Extensions;
  6. using MediaBrowser.Common.Implementations;
  7. using MediaBrowser.Common.Implementations.ScheduledTasks;
  8. using MediaBrowser.Common.IO;
  9. using MediaBrowser.Common.MediaInfo;
  10. using MediaBrowser.Common.Net;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Controller.Configuration;
  13. using MediaBrowser.Controller.Drawing;
  14. using MediaBrowser.Controller.Entities;
  15. using MediaBrowser.Controller.IO;
  16. using MediaBrowser.Controller.Library;
  17. using MediaBrowser.Controller.Localization;
  18. using MediaBrowser.Controller.MediaInfo;
  19. using MediaBrowser.Controller.Persistence;
  20. using MediaBrowser.Controller.Plugins;
  21. using MediaBrowser.Controller.Providers;
  22. using MediaBrowser.Controller.Resolvers;
  23. using MediaBrowser.Controller.Sorting;
  24. using MediaBrowser.Controller.Updates;
  25. using MediaBrowser.Controller.Weather;
  26. using MediaBrowser.IsoMounter;
  27. using MediaBrowser.Model.IO;
  28. using MediaBrowser.Model.MediaInfo;
  29. using MediaBrowser.Model.System;
  30. using MediaBrowser.Model.Updates;
  31. using MediaBrowser.Server.Implementations;
  32. using MediaBrowser.Server.Implementations.BdInfo;
  33. using MediaBrowser.Server.Implementations.Configuration;
  34. using MediaBrowser.Server.Implementations.HttpServer;
  35. using MediaBrowser.Server.Implementations.IO;
  36. using MediaBrowser.Server.Implementations.Library;
  37. using MediaBrowser.Server.Implementations.MediaEncoder;
  38. using MediaBrowser.Server.Implementations.Providers;
  39. using MediaBrowser.Server.Implementations.ServerManager;
  40. using MediaBrowser.Server.Implementations.Udp;
  41. using MediaBrowser.Server.Implementations.Updates;
  42. using MediaBrowser.Server.Implementations.WebSocket;
  43. using MediaBrowser.ServerApplication.Implementations;
  44. using MediaBrowser.WebDashboard.Api;
  45. using System;
  46. using System.Collections.Generic;
  47. using System.Diagnostics;
  48. using System.IO;
  49. using System.Linq;
  50. using System.Net.Sockets;
  51. using System.Reflection;
  52. using System.Threading;
  53. using System.Threading.Tasks;
  54. namespace MediaBrowser.ServerApplication
  55. {
  56. /// <summary>
  57. /// Class CompositionRoot
  58. /// </summary>
  59. public class ApplicationHost : BaseApplicationHost<ServerApplicationPaths>, IServerApplicationHost
  60. {
  61. private const int UdpServerPort = 7359;
  62. /// <summary>
  63. /// Gets the server kernel.
  64. /// </summary>
  65. /// <value>The server kernel.</value>
  66. protected Kernel ServerKernel { get; set; }
  67. /// <summary>
  68. /// Gets the server configuration manager.
  69. /// </summary>
  70. /// <value>The server configuration manager.</value>
  71. public IServerConfigurationManager ServerConfigurationManager
  72. {
  73. get { return (IServerConfigurationManager)ConfigurationManager; }
  74. }
  75. /// <summary>
  76. /// Gets the name of the log file prefix.
  77. /// </summary>
  78. /// <value>The name of the log file prefix.</value>
  79. protected override string LogFilePrefixName
  80. {
  81. get { return "Server"; }
  82. }
  83. /// <summary>
  84. /// Gets the configuration manager.
  85. /// </summary>
  86. /// <returns>IConfigurationManager.</returns>
  87. protected override IConfigurationManager GetConfigurationManager()
  88. {
  89. return new ServerConfigurationManager(ApplicationPaths, LogManager, XmlSerializer);
  90. }
  91. /// <summary>
  92. /// Gets or sets the installation manager.
  93. /// </summary>
  94. /// <value>The installation manager.</value>
  95. private IInstallationManager InstallationManager { get; set; }
  96. /// <summary>
  97. /// Gets or sets the server manager.
  98. /// </summary>
  99. /// <value>The server manager.</value>
  100. private IServerManager ServerManager { get; set; }
  101. /// <summary>
  102. /// Gets or sets the user manager.
  103. /// </summary>
  104. /// <value>The user manager.</value>
  105. public IUserManager UserManager { get; set; }
  106. /// <summary>
  107. /// Gets or sets the library manager.
  108. /// </summary>
  109. /// <value>The library manager.</value>
  110. internal ILibraryManager LibraryManager { get; set; }
  111. /// <summary>
  112. /// Gets or sets the directory watchers.
  113. /// </summary>
  114. /// <value>The directory watchers.</value>
  115. private IDirectoryWatchers DirectoryWatchers { get; set; }
  116. /// <summary>
  117. /// Gets or sets the provider manager.
  118. /// </summary>
  119. /// <value>The provider manager.</value>
  120. private IProviderManager ProviderManager { get; set; }
  121. /// <summary>
  122. /// Gets or sets the zip client.
  123. /// </summary>
  124. /// <value>The zip client.</value>
  125. private IZipClient ZipClient { get; set; }
  126. /// <summary>
  127. /// Gets or sets the HTTP server.
  128. /// </summary>
  129. /// <value>The HTTP server.</value>
  130. private IHttpServer HttpServer { get; set; }
  131. /// <summary>
  132. /// Gets or sets the UDP server.
  133. /// </summary>
  134. /// <value>The UDP server.</value>
  135. private UdpServer UdpServer { get; set; }
  136. /// <summary>
  137. /// Gets or sets the display preferences manager.
  138. /// </summary>
  139. /// <value>The display preferences manager.</value>
  140. internal IDisplayPreferencesManager DisplayPreferencesManager { get; set; }
  141. /// <summary>
  142. /// Gets or sets the media encoder.
  143. /// </summary>
  144. /// <value>The media encoder.</value>
  145. private IMediaEncoder MediaEncoder { get; set; }
  146. /// <summary>
  147. /// The full path to our startmenu shortcut
  148. /// </summary>
  149. protected override string ProductShortcutPath
  150. {
  151. get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), "Media Browser 3", "Media Browser Server.lnk"); }
  152. }
  153. private Task<IHttpServer> _httpServerCreationTask;
  154. /// <summary>
  155. /// Runs the startup tasks.
  156. /// </summary>
  157. /// <returns>Task.</returns>
  158. protected override async Task RunStartupTasks()
  159. {
  160. await base.RunStartupTasks().ConfigureAwait(false);
  161. DirectoryWatchers.Start();
  162. Logger.Info("Core startup complete");
  163. Parallel.ForEach(GetExports<IServerEntryPoint>(), entryPoint => entryPoint.Run());
  164. }
  165. /// <summary>
  166. /// Called when [logger loaded].
  167. /// </summary>
  168. protected override void OnLoggerLoaded()
  169. {
  170. base.OnLoggerLoaded();
  171. _httpServerCreationTask = Task.Run(() => ServerFactory.CreateServer(this, Logger, "Media Browser", "index.html"));
  172. }
  173. /// <summary>
  174. /// Registers resources that classes will depend on
  175. /// </summary>
  176. /// <returns>Task.</returns>
  177. protected override async Task RegisterResources()
  178. {
  179. ServerKernel = new Kernel(ServerConfigurationManager);
  180. await base.RegisterResources().ConfigureAwait(false);
  181. RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager));
  182. RegisterSingleInstance<IServerApplicationHost>(this);
  183. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  184. RegisterSingleInstance(ServerKernel);
  185. RegisterSingleInstance(ServerConfigurationManager);
  186. RegisterSingleInstance<IWebSocketServer>(() => new AlchemyServer(Logger));
  187. RegisterSingleInstance<IIsoManager>(() => new PismoIsoManager(Logger));
  188. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
  189. ZipClient = new DotNetZipClient();
  190. RegisterSingleInstance(ZipClient);
  191. UserManager = new UserManager(Logger, ServerConfigurationManager);
  192. RegisterSingleInstance(UserManager);
  193. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager);
  194. RegisterSingleInstance(LibraryManager);
  195. InstallationManager = new InstallationManager(HttpClient, PackageManager, JsonSerializer, Logger, this);
  196. RegisterSingleInstance(InstallationManager);
  197. DirectoryWatchers = new DirectoryWatchers(LogManager, TaskManager, LibraryManager, ServerConfigurationManager);
  198. RegisterSingleInstance(DirectoryWatchers);
  199. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, DirectoryWatchers, LogManager);
  200. RegisterSingleInstance(ProviderManager);
  201. DisplayPreferencesManager = new DisplayPreferencesManager(LogManager.GetLogger("DisplayPreferencesManager"));
  202. RegisterSingleInstance(DisplayPreferencesManager);
  203. RegisterSingleInstance<ILibrarySearchEngine>(() => new LuceneSearchEngine());
  204. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), ZipClient, ApplicationPaths, JsonSerializer);
  205. RegisterSingleInstance(MediaEncoder);
  206. HttpServer = await _httpServerCreationTask.ConfigureAwait(false);
  207. RegisterSingleInstance(HttpServer, false);
  208. ServerManager = new ServerManager(this, JsonSerializer, Logger, ServerConfigurationManager, ServerKernel);
  209. RegisterSingleInstance(ServerManager);
  210. var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
  211. var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
  212. var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
  213. var userTask = Task.Run(async () => await ConfigureUserRepositories().ConfigureAwait(false));
  214. await Task.WhenAll(itemsTask, userTask, displayPreferencesTask, userdataTask).ConfigureAwait(false);
  215. SetKernelProperties();
  216. }
  217. /// <summary>
  218. /// Sets the kernel properties.
  219. /// </summary>
  220. private void SetKernelProperties()
  221. {
  222. Parallel.Invoke(
  223. () => ServerKernel.FFMpegManager = new FFMpegManager(ApplicationPaths, MediaEncoder, LibraryManager),
  224. () => ServerKernel.ImageManager = new ImageManager(ServerKernel, LogManager.GetLogger("ImageManager"), ApplicationPaths),
  225. () => ServerKernel.WeatherProviders = GetExports<IWeatherProvider>(),
  226. () => ServerKernel.ImageEnhancers = GetExports<IImageEnhancer>().OrderBy(e => e.Priority).ToArray(),
  227. () => ServerKernel.StringFiles = GetExports<LocalizedStringData>(),
  228. SetStaticProperties
  229. );
  230. }
  231. /// <summary>
  232. /// Configures the repositories.
  233. /// </summary>
  234. /// <returns>Task.</returns>
  235. private async Task ConfigureDisplayPreferencesRepositories()
  236. {
  237. var repositories = GetExports<IDisplayPreferencesRepository>();
  238. var repository = GetRepository(repositories, ServerConfigurationManager.Configuration.DisplayPreferencesRepository);
  239. await repository.Initialize().ConfigureAwait(false);
  240. ((DisplayPreferencesManager)DisplayPreferencesManager).Repository = repository;
  241. }
  242. /// <summary>
  243. /// Configures the item repositories.
  244. /// </summary>
  245. /// <returns>Task.</returns>
  246. private async Task ConfigureItemRepositories()
  247. {
  248. var repositories = GetExports<IItemRepository>();
  249. var repository = GetRepository(repositories, ServerConfigurationManager.Configuration.ItemRepository);
  250. await repository.Initialize().ConfigureAwait(false);
  251. ((LibraryManager)LibraryManager).ItemRepository = repository;
  252. }
  253. /// <summary>
  254. /// Configures the user data repositories.
  255. /// </summary>
  256. /// <returns>Task.</returns>
  257. private async Task ConfigureUserDataRepositories()
  258. {
  259. var repositories = GetExports<IUserDataRepository>();
  260. var repository = GetRepository(repositories, ServerConfigurationManager.Configuration.UserDataRepository);
  261. await repository.Initialize().ConfigureAwait(false);
  262. ((UserManager)UserManager).UserDataRepository = repository;
  263. }
  264. private async Task ConfigureUserRepositories()
  265. {
  266. var repositories = GetExports<IUserRepository>();
  267. var repository = GetRepository(repositories, ServerConfigurationManager.Configuration.UserRepository);
  268. await repository.Initialize().ConfigureAwait(false);
  269. ((UserManager)UserManager).UserRepository = repository;
  270. }
  271. /// <summary>
  272. /// Dirty hacks
  273. /// </summary>
  274. private void SetStaticProperties()
  275. {
  276. // For now there's no real way to inject these properly
  277. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  278. BaseItem.ConfigurationManager = ServerConfigurationManager;
  279. BaseItem.LibraryManager = LibraryManager;
  280. BaseItem.ProviderManager = ProviderManager;
  281. User.XmlSerializer = XmlSerializer;
  282. User.UserManager = UserManager;
  283. Ratings.ConfigurationManager = ServerConfigurationManager;
  284. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  285. }
  286. /// <summary>
  287. /// Finds the parts.
  288. /// </summary>
  289. protected override void FindParts()
  290. {
  291. if (IsFirstRun)
  292. {
  293. RegisterServerWithAdministratorAccess();
  294. }
  295. Parallel.Invoke(
  296. () => base.FindParts(),
  297. () =>
  298. {
  299. HttpServer.Init(GetExports<IRestfulService>(false));
  300. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  301. ServerManager.Start();
  302. },
  303. () => LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(), GetExports<IVirtualFolderCreator>(), GetExports<IItemResolver>(), GetExports<IIntroProvider>(), GetExports<IBaseItemComparer>()),
  304. () => ProviderManager.AddMetadataProviders(GetExports<BaseMetadataProvider>().ToArray()),
  305. () =>
  306. {
  307. UdpServer = new UdpServer(Logger, NetworkManager, ServerConfigurationManager);
  308. try
  309. {
  310. UdpServer.Start(UdpServerPort);
  311. }
  312. catch (SocketException ex)
  313. {
  314. Logger.ErrorException("Failed to start UDP Server", ex);
  315. }
  316. }
  317. );
  318. }
  319. /// <summary>
  320. /// Restarts this instance.
  321. /// </summary>
  322. public override void Restart()
  323. {
  324. App.Instance.Restart();
  325. }
  326. /// <summary>
  327. /// Gets or sets a value indicating whether this instance can self update.
  328. /// </summary>
  329. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  330. public override bool CanSelfUpdate
  331. {
  332. get { return ConfigurationManager.CommonConfiguration.EnableAutoUpdate; }
  333. }
  334. /// <summary>
  335. /// Releases unmanaged and - optionally - managed resources.
  336. /// </summary>
  337. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  338. protected override void Dispose(bool dispose)
  339. {
  340. if (dispose)
  341. {
  342. if (UdpServer != null)
  343. {
  344. UdpServer.Dispose();
  345. }
  346. }
  347. base.Dispose(dispose);
  348. }
  349. /// <summary>
  350. /// Checks for update.
  351. /// </summary>
  352. /// <param name="cancellationToken">The cancellation token.</param>
  353. /// <param name="progress">The progress.</param>
  354. /// <returns>Task{CheckForUpdateResult}.</returns>
  355. public async override Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  356. {
  357. var availablePackages = await PackageManager.GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  358. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, Constants.MbServerPkgName, ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  359. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  360. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  361. }
  362. /// <summary>
  363. /// Gets the composable part assemblies.
  364. /// </summary>
  365. /// <returns>IEnumerable{Assembly}.</returns>
  366. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  367. {
  368. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  369. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  370. foreach (var pluginAssembly in Directory
  371. .EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  372. .Select(LoadAssembly).Where(a => a != null))
  373. {
  374. yield return pluginAssembly;
  375. }
  376. // Include composable parts in the Api assembly
  377. yield return typeof(ApiEntryPoint).Assembly;
  378. // Include composable parts in the Dashboard assembly
  379. yield return typeof(DashboardInfo).Assembly;
  380. // Include composable parts in the Model assembly
  381. yield return typeof(SystemInfo).Assembly;
  382. // Include composable parts in the Common assembly
  383. yield return typeof(IApplicationHost).Assembly;
  384. // Include composable parts in the Controller assembly
  385. yield return typeof(Kernel).Assembly;
  386. // Common implementations
  387. yield return typeof(TaskManager).Assembly;
  388. // Server implementations
  389. yield return typeof(ServerApplicationPaths).Assembly;
  390. // Include composable parts in the running assembly
  391. yield return GetType().Assembly;
  392. }
  393. private readonly Guid _systemId = Environment.MachineName.GetMD5();
  394. /// <summary>
  395. /// Gets the system status.
  396. /// </summary>
  397. /// <returns>SystemInfo.</returns>
  398. public virtual SystemInfo GetSystemInfo()
  399. {
  400. return new SystemInfo
  401. {
  402. HasPendingRestart = HasPendingRestart,
  403. Version = ApplicationVersion.ToString(),
  404. IsNetworkDeployed = CanSelfUpdate,
  405. WebSocketPortNumber = ServerManager.WebSocketPortNumber,
  406. SupportsNativeWebSocket = ServerManager.SupportsNativeWebSocket,
  407. FailedPluginAssemblies = FailedAssemblies.ToArray(),
  408. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToArray(),
  409. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  410. Id = _systemId
  411. };
  412. }
  413. /// <summary>
  414. /// Shuts down.
  415. /// </summary>
  416. public override void Shutdown()
  417. {
  418. App.Instance.Dispatcher.Invoke(App.Instance.Shutdown);
  419. }
  420. /// <summary>
  421. /// Registers the server with administrator access.
  422. /// </summary>
  423. private void RegisterServerWithAdministratorAccess()
  424. {
  425. Logger.Info("Requesting administrative access to authorize http server");
  426. // Create a temp file path to extract the bat file to
  427. var tmpFile = Path.Combine(ConfigurationManager.CommonApplicationPaths.TempDirectory, Guid.NewGuid() + ".bat");
  428. // Extract the bat file
  429. using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MediaBrowser.ServerApplication.RegisterServer.bat"))
  430. {
  431. using (var fileStream = File.Create(tmpFile))
  432. {
  433. stream.CopyTo(fileStream);
  434. }
  435. }
  436. var startInfo = new ProcessStartInfo
  437. {
  438. FileName = tmpFile,
  439. Arguments = string.Format("{0} {1} {2} {3}", ServerConfigurationManager.Configuration.HttpServerPortNumber,
  440. ServerKernel.HttpServerUrlPrefix,
  441. UdpServerPort,
  442. ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber),
  443. CreateNoWindow = true,
  444. WindowStyle = ProcessWindowStyle.Hidden,
  445. Verb = "runas",
  446. ErrorDialog = false
  447. };
  448. using (var process = Process.Start(startInfo))
  449. {
  450. process.WaitForExit();
  451. }
  452. }
  453. /// <summary>
  454. /// Gets the repository.
  455. /// </summary>
  456. /// <typeparam name="T"></typeparam>
  457. /// <param name="repositories">The repositories.</param>
  458. /// <param name="name">The name.</param>
  459. /// <returns>``0.</returns>
  460. private T GetRepository<T>(IEnumerable<T> repositories, string name)
  461. where T : class, IRepository
  462. {
  463. var enumerable = repositories as T[] ?? repositories.ToArray();
  464. return enumerable.FirstOrDefault(r => string.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase)) ??
  465. enumerable.FirstOrDefault();
  466. }
  467. }
  468. }