Kernel.cs 21 KB

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