ApplicationHost.cs 22 KB

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