ApplicationHost.cs 22 KB

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