Kernel.cs 22 KB

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