Kernel.cs 22 KB

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