Kernel.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Kernel;
  3. using MediaBrowser.Common.Plugins;
  4. using MediaBrowser.Controller.Drawing;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.IO;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.Localization;
  9. using MediaBrowser.Controller.MediaInfo;
  10. using MediaBrowser.Controller.Persistence;
  11. using MediaBrowser.Controller.Playback;
  12. using MediaBrowser.Controller.Plugins;
  13. using MediaBrowser.Controller.Providers;
  14. using MediaBrowser.Controller.Resolvers;
  15. using MediaBrowser.Controller.ScheduledTasks;
  16. using MediaBrowser.Controller.Updates;
  17. using MediaBrowser.Controller.Weather;
  18. using MediaBrowser.Model.Configuration;
  19. using MediaBrowser.Model.IO;
  20. using MediaBrowser.Model.Logging;
  21. using MediaBrowser.Model.MediaInfo;
  22. using MediaBrowser.Model.System;
  23. using System;
  24. using System.Collections.Generic;
  25. using System.ComponentModel.Composition;
  26. using System.ComponentModel.Composition.Hosting;
  27. using System.Linq;
  28. using System.Threading;
  29. using System.Threading.Tasks;
  30. namespace MediaBrowser.Controller
  31. {
  32. /// <summary>
  33. /// Class Kernel
  34. /// </summary>
  35. public class Kernel : BaseKernel<ServerConfiguration, ServerApplicationPaths>
  36. {
  37. /// <summary>
  38. /// The MB admin URL
  39. /// </summary>
  40. public const string MBAdminUrl = "http://mb3admin.com/admin/";
  41. /// <summary>
  42. /// Gets the instance.
  43. /// </summary>
  44. /// <value>The instance.</value>
  45. public static Kernel Instance { get; private set; }
  46. /// <summary>
  47. /// Gets the library manager.
  48. /// </summary>
  49. /// <value>The library manager.</value>
  50. public LibraryManager LibraryManager { get; private set; }
  51. /// <summary>
  52. /// Gets the image manager.
  53. /// </summary>
  54. /// <value>The image manager.</value>
  55. public ImageManager ImageManager { get; private set; }
  56. /// <summary>
  57. /// Gets the user manager.
  58. /// </summary>
  59. /// <value>The user manager.</value>
  60. public UserManager UserManager { get; private set; }
  61. /// <summary>
  62. /// Gets the FFMPEG controller.
  63. /// </summary>
  64. /// <value>The FFMPEG controller.</value>
  65. public FFMpegManager FFMpegManager { get; private set; }
  66. /// <summary>
  67. /// Gets the installation manager.
  68. /// </summary>
  69. /// <value>The installation manager.</value>
  70. public InstallationManager InstallationManager { get; private set; }
  71. /// <summary>
  72. /// Gets or sets the file system manager.
  73. /// </summary>
  74. /// <value>The file system manager.</value>
  75. public FileSystemManager FileSystemManager { get; private set; }
  76. /// <summary>
  77. /// Gets the provider manager.
  78. /// </summary>
  79. /// <value>The provider manager.</value>
  80. public ProviderManager ProviderManager { get; private set; }
  81. /// <summary>
  82. /// Gets the user data manager.
  83. /// </summary>
  84. /// <value>The user data manager.</value>
  85. public UserDataManager UserDataManager { get; private set; }
  86. /// <summary>
  87. /// Gets the plug-in security manager.
  88. /// </summary>
  89. /// <value>The plug-in security manager.</value>
  90. public PluginSecurityManager PluginSecurityManager { get; private set; }
  91. /// <summary>
  92. /// The _users
  93. /// </summary>
  94. private IEnumerable<User> _users;
  95. /// <summary>
  96. /// The _user lock
  97. /// </summary>
  98. private object _usersSyncLock = new object();
  99. /// <summary>
  100. /// The _users initialized
  101. /// </summary>
  102. private bool _usersInitialized;
  103. /// <summary>
  104. /// Gets the users.
  105. /// </summary>
  106. /// <value>The users.</value>
  107. public IEnumerable<User> Users
  108. {
  109. get
  110. {
  111. // Call ToList to exhaust the stream because we'll be iterating over this multiple times
  112. LazyInitializer.EnsureInitialized(ref _users, ref _usersInitialized, ref _usersSyncLock, UserManager.LoadUsers);
  113. return _users;
  114. }
  115. internal set
  116. {
  117. _users = value;
  118. if (value == null)
  119. {
  120. _usersInitialized = false;
  121. }
  122. }
  123. }
  124. /// <summary>
  125. /// The _root folder
  126. /// </summary>
  127. private AggregateFolder _rootFolder;
  128. /// <summary>
  129. /// The _root folder sync lock
  130. /// </summary>
  131. private object _rootFolderSyncLock = new object();
  132. /// <summary>
  133. /// The _root folder initialized
  134. /// </summary>
  135. private bool _rootFolderInitialized;
  136. /// <summary>
  137. /// Gets the root folder.
  138. /// </summary>
  139. /// <value>The root folder.</value>
  140. public AggregateFolder RootFolder
  141. {
  142. get
  143. {
  144. LazyInitializer.EnsureInitialized(ref _rootFolder, ref _rootFolderInitialized, ref _rootFolderSyncLock, LibraryManager.CreateRootFolder);
  145. return _rootFolder;
  146. }
  147. private set
  148. {
  149. _rootFolder = value;
  150. if (value == null)
  151. {
  152. _rootFolderInitialized = false;
  153. }
  154. }
  155. }
  156. /// <summary>
  157. /// Gets the kernel context.
  158. /// </summary>
  159. /// <value>The kernel context.</value>
  160. public override KernelContext KernelContext
  161. {
  162. get { return KernelContext.Server; }
  163. }
  164. /// <summary>
  165. /// Gets the list of plugin configuration pages
  166. /// </summary>
  167. /// <value>The configuration pages.</value>
  168. [ImportMany(typeof(IPluginConfigurationPage))]
  169. public IEnumerable<IPluginConfigurationPage> PluginConfigurationPages { get; private set; }
  170. /// <summary>
  171. /// Gets the intro providers.
  172. /// </summary>
  173. /// <value>The intro providers.</value>
  174. [ImportMany(typeof(IIntroProvider))]
  175. public IEnumerable<IIntroProvider> IntroProviders { get; private set; }
  176. /// <summary>
  177. /// Gets the list of currently registered weather prvoiders
  178. /// </summary>
  179. /// <value>The weather providers.</value>
  180. [ImportMany(typeof(IWeatherProvider))]
  181. public IEnumerable<IWeatherProvider> WeatherProviders { get; private set; }
  182. /// <summary>
  183. /// Gets the list of currently registered metadata prvoiders
  184. /// </summary>
  185. /// <value>The metadata providers enumerable.</value>
  186. [ImportMany(typeof(BaseMetadataProvider))]
  187. public BaseMetadataProvider[] MetadataProviders { get; private set; }
  188. /// <summary>
  189. /// Gets the list of currently registered image processors
  190. /// Image processors are specialized metadata providers that run after the normal ones
  191. /// </summary>
  192. /// <value>The image enhancers.</value>
  193. [ImportMany(typeof(BaseImageEnhancer))]
  194. public BaseImageEnhancer[] ImageEnhancers { get; private set; }
  195. /// <summary>
  196. /// Gets the list of currently registered entity resolvers
  197. /// </summary>
  198. /// <value>The entity resolvers enumerable.</value>
  199. [ImportMany(typeof(IBaseItemResolver))]
  200. internal IBaseItemResolver[] EntityResolvers { get; private set; }
  201. /// <summary>
  202. /// Gets the list of BasePluginFolders added by plugins
  203. /// </summary>
  204. /// <value>The plugin folders.</value>
  205. [ImportMany(typeof(BasePluginFolder))]
  206. internal IEnumerable<BasePluginFolder> PluginFolders { get; private set; }
  207. /// <summary>
  208. /// Gets the list of available user repositories
  209. /// </summary>
  210. /// <value>The user repositories.</value>
  211. [ImportMany(typeof(IUserRepository))]
  212. private IEnumerable<IUserRepository> UserRepositories { get; set; }
  213. /// <summary>
  214. /// Gets the active user repository
  215. /// </summary>
  216. /// <value>The user repository.</value>
  217. public IUserRepository UserRepository { get; private set; }
  218. /// <summary>
  219. /// Gets the active user repository
  220. /// </summary>
  221. /// <value>The display preferences repository.</value>
  222. public IDisplayPreferencesRepository DisplayPreferencesRepository { get; private set; }
  223. /// <summary>
  224. /// Gets the list of available item repositories
  225. /// </summary>
  226. /// <value>The item repositories.</value>
  227. [ImportMany(typeof(IItemRepository))]
  228. private IEnumerable<IItemRepository> ItemRepositories { get; set; }
  229. /// <summary>
  230. /// Gets the active item repository
  231. /// </summary>
  232. /// <value>The item repository.</value>
  233. public IItemRepository ItemRepository { get; private set; }
  234. /// <summary>
  235. /// Gets the list of available item repositories
  236. /// </summary>
  237. /// <value>The user data repositories.</value>
  238. [ImportMany(typeof(IUserDataRepository))]
  239. private IEnumerable<IUserDataRepository> UserDataRepositories { get; set; }
  240. /// <summary>
  241. /// Gets the list of available DisplayPreferencesRepositories
  242. /// </summary>
  243. /// <value>The display preferences repositories.</value>
  244. [ImportMany(typeof(IDisplayPreferencesRepository))]
  245. private IEnumerable<IDisplayPreferencesRepository> DisplayPreferencesRepositories { get; set; }
  246. /// <summary>
  247. /// Gets the list of entity resolution ignore rules
  248. /// </summary>
  249. /// <value>The entity resolution ignore rules.</value>
  250. [ImportMany(typeof(BaseResolutionIgnoreRule))]
  251. internal IEnumerable<BaseResolutionIgnoreRule> EntityResolutionIgnoreRules { get; private set; }
  252. /// <summary>
  253. /// Gets the active user data repository
  254. /// </summary>
  255. /// <value>The user data repository.</value>
  256. public IUserDataRepository UserDataRepository { get; private set; }
  257. /// <summary>
  258. /// Limits simultaneous access to various resources
  259. /// </summary>
  260. /// <value>The resource pools.</value>
  261. public ResourcePool ResourcePools { get; set; }
  262. /// <summary>
  263. /// Gets the UDP server port number.
  264. /// </summary>
  265. /// <value>The UDP server port number.</value>
  266. public override int UdpServerPortNumber
  267. {
  268. get { return 7359; }
  269. }
  270. /// <summary>
  271. /// Gets or sets the zip client.
  272. /// </summary>
  273. /// <value>The zip client.</value>
  274. private IZipClient ZipClient { get; set; }
  275. /// <summary>
  276. /// Gets or sets the bluray examiner.
  277. /// </summary>
  278. /// <value>The bluray examiner.</value>
  279. private IBlurayExaminer BlurayExaminer { get; set; }
  280. /// <summary>
  281. /// Creates a kernel based on a Data path, which is akin to our current programdata path
  282. /// </summary>
  283. /// <param name="appHost">The app host.</param>
  284. /// <param name="isoManager">The iso manager.</param>
  285. /// <param name="zipClient">The zip client.</param>
  286. /// <param name="blurayExaminer">The bluray examiner.</param>
  287. /// <param name="logger">The logger.</param>
  288. /// <exception cref="System.ArgumentNullException">isoManager</exception>
  289. public Kernel(IApplicationHost appHost, IIsoManager isoManager, IZipClient zipClient, IBlurayExaminer blurayExaminer, ILogger logger)
  290. : base(appHost, isoManager, logger)
  291. {
  292. if (isoManager == null)
  293. {
  294. throw new ArgumentNullException("isoManager");
  295. }
  296. if (zipClient == null)
  297. {
  298. throw new ArgumentNullException("zipClient");
  299. }
  300. if (blurayExaminer == null)
  301. {
  302. throw new ArgumentNullException("blurayExaminer");
  303. }
  304. Instance = this;
  305. ZipClient = zipClient;
  306. BlurayExaminer = blurayExaminer;
  307. // For now there's no real way to inject this properly
  308. BaseItem.Logger = logger;
  309. Ratings.Logger = logger;
  310. LocalizedStrings.Logger = logger;
  311. // For now, until this can become an interface
  312. BaseMetadataProvider.Logger = logger;
  313. }
  314. /// <summary>
  315. /// Composes the exported values.
  316. /// </summary>
  317. /// <param name="container">The container.</param>
  318. protected override void ComposeExportedValues(CompositionContainer container)
  319. {
  320. base.ComposeExportedValues(container);
  321. container.ComposeExportedValue("kernel", this);
  322. container.ComposeExportedValue("blurayExaminer", BlurayExaminer);
  323. }
  324. /// <summary>
  325. /// Performs initializations that can be reloaded at anytime
  326. /// </summary>
  327. /// <returns>Task.</returns>
  328. protected override async Task ReloadInternal()
  329. {
  330. Logger.Info("Extracting tools");
  331. // Reset these so that they can be lazy loaded again
  332. Users = null;
  333. RootFolder = null;
  334. ReloadResourcePools();
  335. InstallationManager = new InstallationManager(this, ZipClient, Logger);
  336. LibraryManager = new LibraryManager(this, Logger);
  337. UserManager = new UserManager(this, Logger);
  338. FFMpegManager = new FFMpegManager(this, ZipClient, Logger);
  339. ImageManager = new ImageManager(this, Logger);
  340. ProviderManager = new ProviderManager(this, Logger);
  341. UserDataManager = new UserDataManager(this, Logger);
  342. PluginSecurityManager = new PluginSecurityManager(this);
  343. await base.ReloadInternal().ConfigureAwait(false);
  344. ReloadFileSystemManager();
  345. await UserManager.RefreshUsersMetadata(CancellationToken.None).ConfigureAwait(false);
  346. }
  347. /// <summary>
  348. /// Releases unmanaged and - optionally - managed resources.
  349. /// </summary>
  350. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  351. protected override void Dispose(bool dispose)
  352. {
  353. if (dispose)
  354. {
  355. DisposeResourcePools();
  356. DisposeFileSystemManager();
  357. }
  358. base.Dispose(dispose);
  359. }
  360. /// <summary>
  361. /// Disposes the resource pools.
  362. /// </summary>
  363. private void DisposeResourcePools()
  364. {
  365. if (ResourcePools != null)
  366. {
  367. ResourcePools.Dispose();
  368. ResourcePools = null;
  369. }
  370. }
  371. /// <summary>
  372. /// Reloads the resource pools.
  373. /// </summary>
  374. private void ReloadResourcePools()
  375. {
  376. DisposeResourcePools();
  377. ResourcePools = new ResourcePool();
  378. }
  379. /// <summary>
  380. /// Called when [composable parts loaded].
  381. /// </summary>
  382. /// <returns>Task.</returns>
  383. protected override async Task OnComposablePartsLoaded()
  384. {
  385. // The base class will start up all the plugins
  386. await base.OnComposablePartsLoaded().ConfigureAwait(false);
  387. // Get the current item repository
  388. ItemRepository = GetRepository(ItemRepositories, Configuration.ItemRepository);
  389. var itemRepoTask = ItemRepository.Initialize();
  390. // Get the current user repository
  391. UserRepository = GetRepository(UserRepositories, Configuration.UserRepository);
  392. var userRepoTask = UserRepository.Initialize();
  393. // Get the current item repository
  394. UserDataRepository = GetRepository(UserDataRepositories, Configuration.UserDataRepository);
  395. var userDataRepoTask = UserDataRepository.Initialize();
  396. // Get the current display preferences repository
  397. DisplayPreferencesRepository = GetRepository(DisplayPreferencesRepositories, Configuration.DisplayPreferencesRepository);
  398. var displayPreferencesRepoTask = DisplayPreferencesRepository.Initialize();
  399. // Sort the resolvers by priority
  400. EntityResolvers = EntityResolvers.OrderBy(e => e.Priority).ToArray();
  401. // Sort the providers by priority
  402. MetadataProviders = MetadataProviders.OrderBy(e => e.Priority).ToArray();
  403. // Sort the image processors by priority
  404. ImageEnhancers = ImageEnhancers.OrderBy(e => e.Priority).ToArray();
  405. await Task.WhenAll(itemRepoTask, userRepoTask, userDataRepoTask, displayPreferencesRepoTask).ConfigureAwait(false);
  406. }
  407. /// <summary>
  408. /// Gets a repository by name from a list, and returns the default if not found
  409. /// </summary>
  410. /// <typeparam name="T"></typeparam>
  411. /// <param name="repositories">The repositories.</param>
  412. /// <param name="name">The name.</param>
  413. /// <returns>``0.</returns>
  414. private T GetRepository<T>(IEnumerable<T> repositories, string name)
  415. where T : class, IRepository
  416. {
  417. var enumerable = repositories as T[] ?? repositories.ToArray();
  418. return enumerable.FirstOrDefault(r => string.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase)) ??
  419. enumerable.FirstOrDefault();
  420. }
  421. /// <summary>
  422. /// Disposes the file system manager.
  423. /// </summary>
  424. private void DisposeFileSystemManager()
  425. {
  426. if (FileSystemManager != null)
  427. {
  428. FileSystemManager.Dispose();
  429. FileSystemManager = null;
  430. }
  431. }
  432. /// <summary>
  433. /// Reloads the file system manager.
  434. /// </summary>
  435. private void ReloadFileSystemManager()
  436. {
  437. DisposeFileSystemManager();
  438. FileSystemManager = new FileSystemManager(this, Logger);
  439. FileSystemManager.StartWatchers();
  440. }
  441. /// <summary>
  442. /// Gets a User by Id
  443. /// </summary>
  444. /// <param name="id">The id.</param>
  445. /// <returns>User.</returns>
  446. /// <exception cref="System.ArgumentNullException"></exception>
  447. public User GetUserById(Guid id)
  448. {
  449. if (id == Guid.Empty)
  450. {
  451. throw new ArgumentNullException();
  452. }
  453. return Users.FirstOrDefault(u => u.Id == id);
  454. }
  455. /// <summary>
  456. /// Finds a library item by Id and UserId.
  457. /// </summary>
  458. /// <param name="id">The id.</param>
  459. /// <param name="userId">The user id.</param>
  460. /// <returns>BaseItem.</returns>
  461. /// <exception cref="System.ArgumentNullException">id</exception>
  462. public BaseItem GetItemById(Guid id, Guid userId)
  463. {
  464. if (id == Guid.Empty)
  465. {
  466. throw new ArgumentNullException("id");
  467. }
  468. if (userId == Guid.Empty)
  469. {
  470. throw new ArgumentNullException("userId");
  471. }
  472. var user = GetUserById(userId);
  473. var userRoot = user.RootFolder;
  474. return userRoot.FindItemById(id, user);
  475. }
  476. /// <summary>
  477. /// Gets the item by id.
  478. /// </summary>
  479. /// <param name="id">The id.</param>
  480. /// <returns>BaseItem.</returns>
  481. /// <exception cref="System.ArgumentNullException">id</exception>
  482. public BaseItem GetItemById(Guid id)
  483. {
  484. if (id == Guid.Empty)
  485. {
  486. throw new ArgumentNullException("id");
  487. }
  488. return RootFolder.FindItemById(id, null);
  489. }
  490. /// <summary>
  491. /// Completely overwrites the current configuration with a new copy
  492. /// </summary>
  493. /// <param name="config">The config.</param>
  494. public void UpdateConfiguration(ServerConfiguration config)
  495. {
  496. var oldConfiguration = Configuration;
  497. var reloadLogger = config.ShowLogWindow != oldConfiguration.ShowLogWindow;
  498. // Figure out whether or not we should refresh people after the update is finished
  499. var refreshPeopleAfterUpdate = !oldConfiguration.EnableInternetProviders && config.EnableInternetProviders;
  500. // This is true if internet providers has just been turned on, or if People have just been removed from InternetProviderExcludeTypes
  501. if (!refreshPeopleAfterUpdate)
  502. {
  503. var oldConfigurationFetchesPeopleImages = oldConfiguration.InternetProviderExcludeTypes == null || !oldConfiguration.InternetProviderExcludeTypes.Contains(typeof(Person).Name, StringComparer.OrdinalIgnoreCase);
  504. var newConfigurationFetchesPeopleImages = config.InternetProviderExcludeTypes == null || !config.InternetProviderExcludeTypes.Contains(typeof(Person).Name, StringComparer.OrdinalIgnoreCase);
  505. refreshPeopleAfterUpdate = newConfigurationFetchesPeopleImages && !oldConfigurationFetchesPeopleImages;
  506. }
  507. Configuration = config;
  508. SaveConfiguration();
  509. if (reloadLogger)
  510. {
  511. ReloadLogger();
  512. }
  513. TcpManager.OnApplicationConfigurationChanged(oldConfiguration, config);
  514. // Validate currently executing providers, in the background
  515. Task.Run(() =>
  516. {
  517. ProviderManager.ValidateCurrentlyRunningProviders();
  518. // Any number of configuration settings could change the way the library is refreshed, so do that now
  519. TaskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  520. if (refreshPeopleAfterUpdate)
  521. {
  522. TaskManager.CancelIfRunningAndQueue<PeopleValidationTask>();
  523. }
  524. });
  525. }
  526. /// <summary>
  527. /// Removes the plugin.
  528. /// </summary>
  529. /// <param name="plugin">The plugin.</param>
  530. internal void RemovePlugin(IPlugin plugin)
  531. {
  532. var list = Plugins.ToList();
  533. list.Remove(plugin);
  534. Plugins = list;
  535. }
  536. /// <summary>
  537. /// Gets the system info.
  538. /// </summary>
  539. /// <returns>SystemInfo.</returns>
  540. public override SystemInfo GetSystemInfo()
  541. {
  542. var info = base.GetSystemInfo();
  543. if (InstallationManager != null)
  544. {
  545. info.InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToArray();
  546. info.CompletedInstallations = InstallationManager.CompletedInstallations.ToArray();
  547. }
  548. return info;
  549. }
  550. }
  551. }