ApplicationHost.cs 23 KB

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