ApplicationHost.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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. /// <summary>
  154. /// Runs the startup tasks.
  155. /// </summary>
  156. /// <returns>Task.</returns>
  157. protected override async Task RunStartupTasks()
  158. {
  159. await base.RunStartupTasks().ConfigureAwait(false);
  160. DirectoryWatchers.Start();
  161. Logger.Info("Core startup complete");
  162. Parallel.ForEach(GetExports<IServerEntryPoint>(), entryPoint => entryPoint.Run());
  163. }
  164. /// <summary>
  165. /// Registers resources that classes will depend on
  166. /// </summary>
  167. /// <returns>Task.</returns>
  168. protected override async Task RegisterResources()
  169. {
  170. ServerKernel = new Kernel(ServerConfigurationManager);
  171. var httpServerTask = Task.Run(() =>
  172. {
  173. HttpServer = ServerFactory.CreateServer(this, Logger, "Media Browser", "index.html");
  174. RegisterSingleInstance(HttpServer, false);
  175. });
  176. await base.RegisterResources().ConfigureAwait(false);
  177. RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager));
  178. RegisterSingleInstance<IServerApplicationHost>(this);
  179. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  180. RegisterSingleInstance(ServerKernel);
  181. RegisterSingleInstance(ServerConfigurationManager);
  182. RegisterSingleInstance<IWebSocketServer>(() => new AlchemyServer(Logger));
  183. RegisterSingleInstance<IIsoManager>(() => new PismoIsoManager(Logger));
  184. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
  185. ZipClient = new DotNetZipClient();
  186. RegisterSingleInstance(ZipClient);
  187. UserManager = new UserManager(Logger, ServerConfigurationManager);
  188. RegisterSingleInstance(UserManager);
  189. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager);
  190. RegisterSingleInstance(LibraryManager);
  191. InstallationManager = new InstallationManager(HttpClient, PackageManager, JsonSerializer, Logger, this);
  192. RegisterSingleInstance(InstallationManager);
  193. DirectoryWatchers = new DirectoryWatchers(LogManager, TaskManager, LibraryManager, ServerConfigurationManager);
  194. RegisterSingleInstance(DirectoryWatchers);
  195. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, DirectoryWatchers, LogManager);
  196. RegisterSingleInstance(ProviderManager);
  197. DisplayPreferencesManager = new DisplayPreferencesManager(LogManager.GetLogger("DisplayPreferencesManager"));
  198. RegisterSingleInstance(DisplayPreferencesManager);
  199. RegisterSingleInstance<ILibrarySearchEngine>(() => new LuceneSearchEngine());
  200. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), ZipClient, ApplicationPaths, JsonSerializer);
  201. RegisterSingleInstance(MediaEncoder);
  202. ServerManager = new ServerManager(this, JsonSerializer, Logger, ServerConfigurationManager, ServerKernel);
  203. RegisterSingleInstance(ServerManager);
  204. var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
  205. var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
  206. var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
  207. var userTask = Task.Run(async () => await ConfigureUserRepositories().ConfigureAwait(false));
  208. await Task.WhenAll(httpServerTask, itemsTask, userTask, displayPreferencesTask, userdataTask).ConfigureAwait(false);
  209. SetKernelProperties();
  210. }
  211. /// <summary>
  212. /// Sets the kernel properties.
  213. /// </summary>
  214. private void SetKernelProperties()
  215. {
  216. Parallel.Invoke(
  217. () => ServerKernel.FFMpegManager = new FFMpegManager(ApplicationPaths, MediaEncoder, LibraryManager),
  218. () => ServerKernel.ImageManager = new ImageManager(ServerKernel, LogManager.GetLogger("ImageManager"), ApplicationPaths),
  219. () => ServerKernel.WeatherProviders = GetExports<IWeatherProvider>(),
  220. () => ServerKernel.ImageEnhancers = GetExports<IImageEnhancer>().OrderBy(e => e.Priority).ToArray(),
  221. () => ServerKernel.StringFiles = GetExports<LocalizedStringData>(),
  222. SetStaticProperties
  223. );
  224. }
  225. /// <summary>
  226. /// Configures the repositories.
  227. /// </summary>
  228. /// <returns>Task.</returns>
  229. private async Task ConfigureDisplayPreferencesRepositories()
  230. {
  231. var repositories = GetExports<IDisplayPreferencesRepository>();
  232. var repository = GetRepository(repositories, ServerConfigurationManager.Configuration.DisplayPreferencesRepository);
  233. await repository.Initialize().ConfigureAwait(false);
  234. ((DisplayPreferencesManager)DisplayPreferencesManager).Repository = repository;
  235. }
  236. /// <summary>
  237. /// Configures the item repositories.
  238. /// </summary>
  239. /// <returns>Task.</returns>
  240. private async Task ConfigureItemRepositories()
  241. {
  242. var repositories = GetExports<IItemRepository>();
  243. var repository = GetRepository(repositories, ServerConfigurationManager.Configuration.ItemRepository);
  244. await repository.Initialize().ConfigureAwait(false);
  245. ((LibraryManager)LibraryManager).ItemRepository = repository;
  246. }
  247. /// <summary>
  248. /// Configures the user data repositories.
  249. /// </summary>
  250. /// <returns>Task.</returns>
  251. private async Task ConfigureUserDataRepositories()
  252. {
  253. var repositories = GetExports<IUserDataRepository>();
  254. var repository = GetRepository(repositories, ServerConfigurationManager.Configuration.UserDataRepository);
  255. await repository.Initialize().ConfigureAwait(false);
  256. ((UserManager)UserManager).UserDataRepository = repository;
  257. }
  258. private async Task ConfigureUserRepositories()
  259. {
  260. var repositories = GetExports<IUserRepository>();
  261. var repository = GetRepository(repositories, ServerConfigurationManager.Configuration.UserRepository);
  262. await repository.Initialize().ConfigureAwait(false);
  263. ((UserManager)UserManager).UserRepository = repository;
  264. }
  265. /// <summary>
  266. /// Dirty hacks
  267. /// </summary>
  268. private void SetStaticProperties()
  269. {
  270. // For now there's no real way to inject these properly
  271. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  272. BaseItem.ConfigurationManager = ServerConfigurationManager;
  273. BaseItem.LibraryManager = LibraryManager;
  274. BaseItem.ProviderManager = ProviderManager;
  275. User.XmlSerializer = XmlSerializer;
  276. User.UserManager = UserManager;
  277. Ratings.ConfigurationManager = ServerConfigurationManager;
  278. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  279. }
  280. /// <summary>
  281. /// Finds the parts.
  282. /// </summary>
  283. protected override void FindParts()
  284. {
  285. if (IsFirstRun)
  286. {
  287. RegisterServerWithAdministratorAccess();
  288. }
  289. Parallel.Invoke(
  290. () => base.FindParts(),
  291. () =>
  292. {
  293. HttpServer.Init(GetExports<IRestfulService>(false));
  294. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  295. ServerManager.Start();
  296. },
  297. () => LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(), GetExports<IVirtualFolderCreator>(), GetExports<IItemResolver>(), GetExports<IIntroProvider>(), GetExports<IBaseItemComparer>()),
  298. () => ProviderManager.AddMetadataProviders(GetExports<BaseMetadataProvider>().ToArray()),
  299. () =>
  300. {
  301. UdpServer = new UdpServer(Logger, NetworkManager, ServerConfigurationManager);
  302. try
  303. {
  304. UdpServer.Start(UdpServerPort);
  305. }
  306. catch (SocketException ex)
  307. {
  308. Logger.ErrorException("Failed to start UDP Server", ex);
  309. }
  310. }
  311. );
  312. }
  313. /// <summary>
  314. /// Restarts this instance.
  315. /// </summary>
  316. public override void Restart()
  317. {
  318. App.Instance.Restart();
  319. }
  320. /// <summary>
  321. /// Gets or sets a value indicating whether this instance can self update.
  322. /// </summary>
  323. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  324. public override bool CanSelfUpdate
  325. {
  326. get { return ConfigurationManager.CommonConfiguration.EnableAutoUpdate; }
  327. }
  328. /// <summary>
  329. /// Releases unmanaged and - optionally - managed resources.
  330. /// </summary>
  331. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  332. protected override void Dispose(bool dispose)
  333. {
  334. if (dispose)
  335. {
  336. if (UdpServer != null)
  337. {
  338. UdpServer.Dispose();
  339. }
  340. }
  341. base.Dispose(dispose);
  342. }
  343. /// <summary>
  344. /// Checks for update.
  345. /// </summary>
  346. /// <param name="cancellationToken">The cancellation token.</param>
  347. /// <param name="progress">The progress.</param>
  348. /// <returns>Task{CheckForUpdateResult}.</returns>
  349. public async override Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  350. {
  351. var availablePackages = await PackageManager.GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  352. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, Constants.MBServerPkgName, ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  353. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  354. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  355. }
  356. /// <summary>
  357. /// Gets the composable part assemblies.
  358. /// </summary>
  359. /// <returns>IEnumerable{Assembly}.</returns>
  360. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  361. {
  362. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  363. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  364. foreach (var pluginAssembly in Directory
  365. .EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  366. .Select(LoadAssembly).Where(a => a != null))
  367. {
  368. yield return pluginAssembly;
  369. }
  370. // Include composable parts in the Api assembly
  371. yield return typeof(ApiEntryPoint).Assembly;
  372. // Include composable parts in the Dashboard assembly
  373. yield return typeof(DashboardInfo).Assembly;
  374. // Include composable parts in the Model assembly
  375. yield return typeof(SystemInfo).Assembly;
  376. // Include composable parts in the Common assembly
  377. yield return typeof(IApplicationHost).Assembly;
  378. // Include composable parts in the Controller assembly
  379. yield return typeof(Kernel).Assembly;
  380. // Common implementations
  381. yield return typeof(TaskManager).Assembly;
  382. // Server implementations
  383. yield return typeof(ServerApplicationPaths).Assembly;
  384. // Include composable parts in the running assembly
  385. yield return GetType().Assembly;
  386. }
  387. private readonly Guid _systemId = Environment.MachineName.GetMD5();
  388. /// <summary>
  389. /// Gets the system status.
  390. /// </summary>
  391. /// <returns>SystemInfo.</returns>
  392. public virtual SystemInfo GetSystemInfo()
  393. {
  394. return new SystemInfo
  395. {
  396. HasPendingRestart = HasPendingRestart,
  397. Version = ApplicationVersion.ToString(),
  398. IsNetworkDeployed = CanSelfUpdate,
  399. WebSocketPortNumber = ServerManager.WebSocketPortNumber,
  400. SupportsNativeWebSocket = ServerManager.SupportsNativeWebSocket,
  401. FailedPluginAssemblies = FailedAssemblies.ToArray(),
  402. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToArray(),
  403. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  404. Id = _systemId
  405. };
  406. }
  407. /// <summary>
  408. /// Shuts down.
  409. /// </summary>
  410. public override void Shutdown()
  411. {
  412. App.Instance.Dispatcher.Invoke(App.Instance.Shutdown);
  413. }
  414. /// <summary>
  415. /// Registers the server with administrator access.
  416. /// </summary>
  417. private void RegisterServerWithAdministratorAccess()
  418. {
  419. Logger.Info("Requesting administrative access to authorize http server");
  420. // Create a temp file path to extract the bat file to
  421. var tmpFile = Path.Combine(ConfigurationManager.CommonApplicationPaths.TempDirectory, Guid.NewGuid() + ".bat");
  422. // Extract the bat file
  423. using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MediaBrowser.ServerApplication.RegisterServer.bat"))
  424. {
  425. using (var fileStream = File.Create(tmpFile))
  426. {
  427. stream.CopyTo(fileStream);
  428. }
  429. }
  430. var startInfo = new ProcessStartInfo
  431. {
  432. FileName = tmpFile,
  433. Arguments = string.Format("{0} {1} {2} {3}", ServerConfigurationManager.Configuration.HttpServerPortNumber,
  434. ServerKernel.HttpServerUrlPrefix,
  435. UdpServerPort,
  436. ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber),
  437. CreateNoWindow = true,
  438. WindowStyle = ProcessWindowStyle.Hidden,
  439. Verb = "runas",
  440. ErrorDialog = false
  441. };
  442. using (var process = Process.Start(startInfo))
  443. {
  444. process.WaitForExit();
  445. }
  446. }
  447. /// <summary>
  448. /// Gets the repository.
  449. /// </summary>
  450. /// <typeparam name="T"></typeparam>
  451. /// <param name="repositories">The repositories.</param>
  452. /// <param name="name">The name.</param>
  453. /// <returns>``0.</returns>
  454. private T GetRepository<T>(IEnumerable<T> repositories, string name)
  455. where T : class, IRepository
  456. {
  457. var enumerable = repositories as T[] ?? repositories.ToArray();
  458. return enumerable.FirstOrDefault(r => string.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase)) ??
  459. enumerable.FirstOrDefault();
  460. }
  461. }
  462. }