Kernel.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. using MediaBrowser.Common.Kernel;
  2. using MediaBrowser.Common.Plugins;
  3. using MediaBrowser.Common.ScheduledTasks;
  4. using MediaBrowser.Common.Security;
  5. using MediaBrowser.Common.Updates;
  6. using MediaBrowser.Controller.Drawing;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.IO;
  9. using MediaBrowser.Controller.Library;
  10. using MediaBrowser.Controller.Localization;
  11. using MediaBrowser.Controller.MediaInfo;
  12. using MediaBrowser.Controller.Persistence;
  13. using MediaBrowser.Controller.Playback;
  14. using MediaBrowser.Controller.Plugins;
  15. using MediaBrowser.Controller.Providers;
  16. using MediaBrowser.Controller.Resolvers;
  17. using MediaBrowser.Controller.Updates;
  18. using MediaBrowser.Controller.Weather;
  19. using MediaBrowser.Model.Configuration;
  20. using MediaBrowser.Model.Logging;
  21. using MediaBrowser.Model.Serialization;
  22. using MediaBrowser.Model.System;
  23. using System;
  24. using System.Collections.Generic;
  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, IServerApplicationPaths>
  34. {
  35. /// <summary>
  36. /// Gets the instance.
  37. /// </summary>
  38. /// <value>The instance.</value>
  39. public static Kernel Instance { get; private set; }
  40. /// <summary>
  41. /// Gets the library manager.
  42. /// </summary>
  43. /// <value>The library manager.</value>
  44. public LibraryManager LibraryManager { get; private set; }
  45. /// <summary>
  46. /// Gets the image manager.
  47. /// </summary>
  48. /// <value>The image manager.</value>
  49. public ImageManager ImageManager { get; private set; }
  50. /// <summary>
  51. /// Gets the user manager.
  52. /// </summary>
  53. /// <value>The user manager.</value>
  54. public UserManager UserManager { get; private set; }
  55. /// <summary>
  56. /// Gets the FFMPEG controller.
  57. /// </summary>
  58. /// <value>The FFMPEG controller.</value>
  59. public FFMpegManager FFMpegManager { get; private set; }
  60. /// <summary>
  61. /// Gets the installation manager.
  62. /// </summary>
  63. /// <value>The installation manager.</value>
  64. public InstallationManager InstallationManager { get; private set; }
  65. /// <summary>
  66. /// Gets or sets the file system manager.
  67. /// </summary>
  68. /// <value>The file system manager.</value>
  69. public FileSystemManager FileSystemManager { get; private set; }
  70. /// <summary>
  71. /// Gets the provider manager.
  72. /// </summary>
  73. /// <value>The provider manager.</value>
  74. public ProviderManager ProviderManager { get; private set; }
  75. /// <summary>
  76. /// Gets the user data manager.
  77. /// </summary>
  78. /// <value>The user data manager.</value>
  79. public UserDataManager UserDataManager { get; private set; }
  80. /// <summary>
  81. /// The _users
  82. /// </summary>
  83. private IEnumerable<User> _users;
  84. /// <summary>
  85. /// The _user lock
  86. /// </summary>
  87. private object _usersSyncLock = new object();
  88. /// <summary>
  89. /// The _users initialized
  90. /// </summary>
  91. private bool _usersInitialized;
  92. /// <summary>
  93. /// Gets the users.
  94. /// </summary>
  95. /// <value>The users.</value>
  96. public IEnumerable<User> Users
  97. {
  98. get
  99. {
  100. // Call ToList to exhaust the stream because we'll be iterating over this multiple times
  101. LazyInitializer.EnsureInitialized(ref _users, ref _usersInitialized, ref _usersSyncLock, UserManager.LoadUsers);
  102. return _users;
  103. }
  104. internal set
  105. {
  106. _users = value;
  107. if (value == null)
  108. {
  109. _usersInitialized = false;
  110. }
  111. }
  112. }
  113. /// <summary>
  114. /// The _root folder
  115. /// </summary>
  116. private AggregateFolder _rootFolder;
  117. /// <summary>
  118. /// The _root folder sync lock
  119. /// </summary>
  120. private object _rootFolderSyncLock = new object();
  121. /// <summary>
  122. /// The _root folder initialized
  123. /// </summary>
  124. private bool _rootFolderInitialized;
  125. /// <summary>
  126. /// Gets the root folder.
  127. /// </summary>
  128. /// <value>The root folder.</value>
  129. public AggregateFolder RootFolder
  130. {
  131. get
  132. {
  133. LazyInitializer.EnsureInitialized(ref _rootFolder, ref _rootFolderInitialized, ref _rootFolderSyncLock, LibraryManager.CreateRootFolder);
  134. return _rootFolder;
  135. }
  136. private set
  137. {
  138. _rootFolder = value;
  139. if (value == null)
  140. {
  141. _rootFolderInitialized = false;
  142. }
  143. }
  144. }
  145. /// <summary>
  146. /// Gets the kernel context.
  147. /// </summary>
  148. /// <value>The kernel context.</value>
  149. public override KernelContext KernelContext
  150. {
  151. get { return KernelContext.Server; }
  152. }
  153. /// <summary>
  154. /// Gets the list of Localized string files
  155. /// </summary>
  156. /// <value>The string files.</value>
  157. public IEnumerable<LocalizedStringData> StringFiles { get; private set; }
  158. /// <summary>
  159. /// Gets the list of plugin configuration pages
  160. /// </summary>
  161. /// <value>The configuration pages.</value>
  162. public IEnumerable<IPluginConfigurationPage> PluginConfigurationPages { get; private set; }
  163. /// <summary>
  164. /// Gets the intro providers.
  165. /// </summary>
  166. /// <value>The intro providers.</value>
  167. public IEnumerable<IIntroProvider> IntroProviders { get; private set; }
  168. /// <summary>
  169. /// Gets the list of currently registered weather prvoiders
  170. /// </summary>
  171. /// <value>The weather providers.</value>
  172. public IEnumerable<IWeatherProvider> WeatherProviders { get; private set; }
  173. /// <summary>
  174. /// Gets the list of currently registered metadata prvoiders
  175. /// </summary>
  176. /// <value>The metadata providers enumerable.</value>
  177. public BaseMetadataProvider[] MetadataProviders { get; private set; }
  178. /// <summary>
  179. /// Gets the list of currently registered image processors
  180. /// Image processors are specialized metadata providers that run after the normal ones
  181. /// </summary>
  182. /// <value>The image enhancers.</value>
  183. public IEnumerable<IImageEnhancer> ImageEnhancers { get; private set; }
  184. /// <summary>
  185. /// Gets the list of currently registered entity resolvers
  186. /// </summary>
  187. /// <value>The entity resolvers enumerable.</value>
  188. internal IEnumerable<IBaseItemResolver> EntityResolvers { get; private set; }
  189. /// <summary>
  190. /// Gets the list of BasePluginFolders added by plugins
  191. /// </summary>
  192. /// <value>The plugin folders.</value>
  193. internal IEnumerable<IVirtualFolderCreator> PluginFolderCreators { get; private set; }
  194. /// <summary>
  195. /// Gets the list of available user repositories
  196. /// </summary>
  197. /// <value>The user repositories.</value>
  198. private IEnumerable<IUserRepository> UserRepositories { get; set; }
  199. /// <summary>
  200. /// Gets the active user repository
  201. /// </summary>
  202. /// <value>The user repository.</value>
  203. public IUserRepository UserRepository { get; private set; }
  204. /// <summary>
  205. /// Gets the active user repository
  206. /// </summary>
  207. /// <value>The display preferences repository.</value>
  208. public IDisplayPreferencesRepository DisplayPreferencesRepository { get; private set; }
  209. /// <summary>
  210. /// Gets the list of available item repositories
  211. /// </summary>
  212. /// <value>The item repositories.</value>
  213. private IEnumerable<IItemRepository> ItemRepositories { get; set; }
  214. /// <summary>
  215. /// Gets the active item repository
  216. /// </summary>
  217. /// <value>The item repository.</value>
  218. public IItemRepository ItemRepository { get; private set; }
  219. /// <summary>
  220. /// Gets the list of available item repositories
  221. /// </summary>
  222. /// <value>The user data repositories.</value>
  223. private IEnumerable<IUserDataRepository> UserDataRepositories { get; set; }
  224. /// <summary>
  225. /// Gets the list of available DisplayPreferencesRepositories
  226. /// </summary>
  227. /// <value>The display preferences repositories.</value>
  228. private IEnumerable<IDisplayPreferencesRepository> DisplayPreferencesRepositories { get; set; }
  229. /// <summary>
  230. /// Gets the list of entity resolution ignore rules
  231. /// </summary>
  232. /// <value>The entity resolution ignore rules.</value>
  233. internal IEnumerable<IResolutionIgnoreRule> EntityResolutionIgnoreRules { get; private set; }
  234. /// <summary>
  235. /// Gets the active user data repository
  236. /// </summary>
  237. /// <value>The user data repository.</value>
  238. public IUserDataRepository UserDataRepository { get; private set; }
  239. /// <summary>
  240. /// Gets the UDP server port number.
  241. /// </summary>
  242. /// <value>The UDP server port number.</value>
  243. public override int UdpServerPortNumber
  244. {
  245. get { return 7359; }
  246. }
  247. /// <summary>
  248. /// Creates a kernel based on a Data path, which is akin to our current programdata path
  249. /// </summary>
  250. /// <param name="appHost">The app host.</param>
  251. /// <param name="appPaths">The app paths.</param>
  252. /// <param name="xmlSerializer">The XML serializer.</param>
  253. /// <param name="taskManager">The task manager.</param>
  254. /// <param name="logger">The logger.</param>
  255. /// <exception cref="System.ArgumentNullException">isoManager</exception>
  256. public Kernel(IApplicationHost appHost, IServerApplicationPaths appPaths, IXmlSerializer xmlSerializer, ILogger logger)
  257. : base(appHost, appPaths, xmlSerializer, logger)
  258. {
  259. Instance = this;
  260. // For now there's no real way to inject this properly
  261. BaseItem.Logger = logger;
  262. Ratings.Logger = logger;
  263. LocalizedStrings.Logger = logger;
  264. // For now, until this can become an interface
  265. BaseMetadataProvider.Logger = logger;
  266. }
  267. /// <summary>
  268. /// Composes the parts with ioc container.
  269. /// </summary>
  270. protected override void FindParts()
  271. {
  272. InstallationManager = (InstallationManager)ApplicationHost.CreateInstance(typeof(InstallationManager));
  273. FFMpegManager = (FFMpegManager)ApplicationHost.CreateInstance(typeof(FFMpegManager));
  274. LibraryManager = (LibraryManager)ApplicationHost.CreateInstance(typeof(LibraryManager));
  275. UserManager = (UserManager)ApplicationHost.CreateInstance(typeof(UserManager));
  276. ImageManager = (ImageManager)ApplicationHost.CreateInstance(typeof(ImageManager));
  277. ProviderManager = (ProviderManager)ApplicationHost.CreateInstance(typeof(ProviderManager));
  278. UserDataManager = (UserDataManager)ApplicationHost.CreateInstance(typeof(UserDataManager));
  279. SecurityManager = (PluginSecurityManager)ApplicationHost.CreateInstance(typeof(PluginSecurityManager));
  280. base.FindParts();
  281. EntityResolutionIgnoreRules = ApplicationHost.GetExports<IResolutionIgnoreRule>();
  282. UserDataRepositories = ApplicationHost.GetExports<IUserDataRepository>();
  283. UserRepositories = ApplicationHost.GetExports<IUserRepository>();
  284. DisplayPreferencesRepositories = ApplicationHost.GetExports<IDisplayPreferencesRepository>();
  285. ItemRepositories = ApplicationHost.GetExports<IItemRepository>();
  286. WeatherProviders = ApplicationHost.GetExports<IWeatherProvider>();
  287. IntroProviders = ApplicationHost.GetExports<IIntroProvider>();
  288. PluginConfigurationPages = ApplicationHost.GetExports<IPluginConfigurationPage>();
  289. ImageEnhancers = ApplicationHost.GetExports<IImageEnhancer>().OrderBy(e => e.Priority).ToArray();
  290. PluginFolderCreators = ApplicationHost.GetExports<IVirtualFolderCreator>();
  291. StringFiles = ApplicationHost.GetExports<LocalizedStringData>();
  292. EntityResolvers = ApplicationHost.GetExports<IBaseItemResolver>().OrderBy(e => e.Priority).ToArray();
  293. MetadataProviders = ApplicationHost.GetExports<BaseMetadataProvider>().OrderBy(e => e.Priority).ToArray();
  294. }
  295. /// <summary>
  296. /// Performs initializations that can be reloaded at anytime
  297. /// </summary>
  298. /// <returns>Task.</returns>
  299. protected override async Task ReloadInternal()
  300. {
  301. // Reset these so that they can be lazy loaded again
  302. Users = null;
  303. RootFolder = null;
  304. await base.ReloadInternal().ConfigureAwait(false);
  305. ReloadResourcePools();
  306. ReloadFileSystemManager();
  307. await UserManager.RefreshUsersMetadata(CancellationToken.None).ConfigureAwait(false);
  308. }
  309. /// <summary>
  310. /// Releases unmanaged and - optionally - managed resources.
  311. /// </summary>
  312. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  313. protected override void Dispose(bool dispose)
  314. {
  315. if (dispose)
  316. {
  317. DisposeResourcePools();
  318. DisposeFileSystemManager();
  319. }
  320. base.Dispose(dispose);
  321. }
  322. /// <summary>
  323. /// Disposes the resource pools.
  324. /// </summary>
  325. private void DisposeResourcePools()
  326. {
  327. if (ResourcePools != null)
  328. {
  329. ResourcePools.Dispose();
  330. ResourcePools = null;
  331. }
  332. }
  333. /// <summary>
  334. /// Reloads the resource pools.
  335. /// </summary>
  336. private void ReloadResourcePools()
  337. {
  338. DisposeResourcePools();
  339. ResourcePools = new ResourcePool();
  340. }
  341. /// <summary>
  342. /// Called when [composable parts loaded].
  343. /// </summary>
  344. /// <returns>Task.</returns>
  345. protected override async Task OnComposablePartsLoaded()
  346. {
  347. // The base class will start up all the plugins
  348. await base.OnComposablePartsLoaded().ConfigureAwait(false);
  349. // Get the current item repository
  350. ItemRepository = GetRepository(ItemRepositories, Configuration.ItemRepository);
  351. var itemRepoTask = ItemRepository.Initialize();
  352. // Get the current user repository
  353. UserRepository = GetRepository(UserRepositories, Configuration.UserRepository);
  354. var userRepoTask = UserRepository.Initialize();
  355. // Get the current item repository
  356. UserDataRepository = GetRepository(UserDataRepositories, Configuration.UserDataRepository);
  357. var userDataRepoTask = UserDataRepository.Initialize();
  358. // Get the current display preferences repository
  359. DisplayPreferencesRepository = GetRepository(DisplayPreferencesRepositories, Configuration.DisplayPreferencesRepository);
  360. var displayPreferencesRepoTask = DisplayPreferencesRepository.Initialize();
  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, Logger, ApplicationHost.Resolve<ITaskManager>());
  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. Configuration = config;
  453. SaveConfiguration();
  454. // Validate currently executing providers, in the background
  455. Task.Run(() =>
  456. {
  457. ProviderManager.ValidateCurrentlyRunningProviders();
  458. });
  459. }
  460. /// <summary>
  461. /// Gets the system info.
  462. /// </summary>
  463. /// <returns>SystemInfo.</returns>
  464. public override SystemInfo GetSystemInfo()
  465. {
  466. var info = base.GetSystemInfo();
  467. if (InstallationManager != null)
  468. {
  469. info.InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToArray();
  470. info.CompletedInstallations = InstallationManager.CompletedInstallations.ToArray();
  471. }
  472. return info;
  473. }
  474. }
  475. }