Kernel.cs 18 KB

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