2
0

ApplicationHost.cs 22 KB

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