Kernel.cs 22 KB

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