Kernel.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. using MediaBrowser.Common.Kernel;
  2. using MediaBrowser.Common.Plugins;
  3. using MediaBrowser.Common.ScheduledTasks;
  4. using MediaBrowser.Common.Updates;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.IO;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.Localization;
  10. using MediaBrowser.Controller.MediaInfo;
  11. using MediaBrowser.Controller.Persistence;
  12. using MediaBrowser.Controller.Playback;
  13. using MediaBrowser.Controller.Plugins;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Controller.Resolvers;
  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 IInstallationManager 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. /// <summary>
  261. /// Creates a kernel based on a Data path, which is akin to our current programdata path
  262. /// </summary>
  263. /// <param name="appHost">The app host.</param>
  264. /// <param name="appPaths">The app paths.</param>
  265. /// <param name="xmlSerializer">The XML serializer.</param>
  266. /// <param name="taskManager">The task manager.</param>
  267. /// <param name="logger">The logger.</param>
  268. /// <exception cref="System.ArgumentNullException">isoManager</exception>
  269. public Kernel(IApplicationHost appHost, IServerApplicationPaths appPaths, IXmlSerializer xmlSerializer, ILogger logger)
  270. : base(appHost, appPaths, xmlSerializer, logger)
  271. {
  272. Instance = this;
  273. // For now there's no real way to inject this properly
  274. BaseItem.Logger = logger;
  275. Ratings.Logger = logger;
  276. LocalizedStrings.Logger = logger;
  277. // For now, until this can become an interface
  278. BaseMetadataProvider.Logger = logger;
  279. }
  280. /// <summary>
  281. /// Composes the parts with ioc container.
  282. /// </summary>
  283. protected override void FindParts()
  284. {
  285. InstallationManager = (InstallationManager)ApplicationHost.CreateInstance(typeof(InstallationManager));
  286. FFMpegManager = (FFMpegManager)ApplicationHost.CreateInstance(typeof(FFMpegManager));
  287. LibraryManager = (LibraryManager)ApplicationHost.CreateInstance(typeof(LibraryManager));
  288. UserManager = (UserManager)ApplicationHost.CreateInstance(typeof(UserManager));
  289. ImageManager = (ImageManager)ApplicationHost.CreateInstance(typeof(ImageManager));
  290. ProviderManager = (ProviderManager)ApplicationHost.CreateInstance(typeof(ProviderManager));
  291. UserDataManager = (UserDataManager)ApplicationHost.CreateInstance(typeof(UserDataManager));
  292. PluginSecurityManager = (PluginSecurityManager)ApplicationHost.CreateInstance(typeof(PluginSecurityManager));
  293. base.FindParts();
  294. EntityResolutionIgnoreRules = ApplicationHost.GetExports<IResolutionIgnoreRule>();
  295. UserDataRepositories = ApplicationHost.GetExports<IUserDataRepository>();
  296. UserRepositories = ApplicationHost.GetExports<IUserRepository>();
  297. DisplayPreferencesRepositories = ApplicationHost.GetExports<IDisplayPreferencesRepository>();
  298. ItemRepositories = ApplicationHost.GetExports<IItemRepository>();
  299. WeatherProviders = ApplicationHost.GetExports<IWeatherProvider>();
  300. IntroProviders = ApplicationHost.GetExports<IIntroProvider>();
  301. PluginConfigurationPages = ApplicationHost.GetExports<IPluginConfigurationPage>();
  302. ImageEnhancers = ApplicationHost.GetExports<IImageEnhancer>().OrderBy(e => e.Priority).ToArray();
  303. PluginFolderCreators = ApplicationHost.GetExports<IVirtualFolderCreator>();
  304. StringFiles = ApplicationHost.GetExports<LocalizedStringData>();
  305. EntityResolvers = ApplicationHost.GetExports<IBaseItemResolver>().OrderBy(e => e.Priority).ToArray();
  306. MetadataProviders = ApplicationHost.GetExports<BaseMetadataProvider>().OrderBy(e => e.Priority).ToArray();
  307. }
  308. /// <summary>
  309. /// Performs initializations that can be reloaded at anytime
  310. /// </summary>
  311. /// <returns>Task.</returns>
  312. protected override async Task ReloadInternal()
  313. {
  314. // Reset these so that they can be lazy loaded again
  315. Users = null;
  316. RootFolder = null;
  317. await base.ReloadInternal().ConfigureAwait(false);
  318. ReloadResourcePools();
  319. ReloadFileSystemManager();
  320. await UserManager.RefreshUsersMetadata(CancellationToken.None).ConfigureAwait(false);
  321. }
  322. /// <summary>
  323. /// Releases unmanaged and - optionally - managed resources.
  324. /// </summary>
  325. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  326. protected override void Dispose(bool dispose)
  327. {
  328. if (dispose)
  329. {
  330. DisposeResourcePools();
  331. DisposeFileSystemManager();
  332. }
  333. base.Dispose(dispose);
  334. }
  335. /// <summary>
  336. /// Disposes the resource pools.
  337. /// </summary>
  338. private void DisposeResourcePools()
  339. {
  340. if (ResourcePools != null)
  341. {
  342. ResourcePools.Dispose();
  343. ResourcePools = null;
  344. }
  345. }
  346. /// <summary>
  347. /// Reloads the resource pools.
  348. /// </summary>
  349. private void ReloadResourcePools()
  350. {
  351. DisposeResourcePools();
  352. ResourcePools = new ResourcePool();
  353. }
  354. /// <summary>
  355. /// Called when [composable parts loaded].
  356. /// </summary>
  357. /// <returns>Task.</returns>
  358. protected override async Task OnComposablePartsLoaded()
  359. {
  360. // The base class will start up all the plugins
  361. await base.OnComposablePartsLoaded().ConfigureAwait(false);
  362. // Get the current item repository
  363. ItemRepository = GetRepository(ItemRepositories, Configuration.ItemRepository);
  364. var itemRepoTask = ItemRepository.Initialize();
  365. // Get the current user repository
  366. UserRepository = GetRepository(UserRepositories, Configuration.UserRepository);
  367. var userRepoTask = UserRepository.Initialize();
  368. // Get the current item repository
  369. UserDataRepository = GetRepository(UserDataRepositories, Configuration.UserDataRepository);
  370. var userDataRepoTask = UserDataRepository.Initialize();
  371. // Get the current display preferences repository
  372. DisplayPreferencesRepository = GetRepository(DisplayPreferencesRepositories, Configuration.DisplayPreferencesRepository);
  373. var displayPreferencesRepoTask = DisplayPreferencesRepository.Initialize();
  374. await Task.WhenAll(itemRepoTask, userRepoTask, userDataRepoTask, displayPreferencesRepoTask).ConfigureAwait(false);
  375. }
  376. /// <summary>
  377. /// Gets a repository by name from a list, and returns the default if not found
  378. /// </summary>
  379. /// <typeparam name="T"></typeparam>
  380. /// <param name="repositories">The repositories.</param>
  381. /// <param name="name">The name.</param>
  382. /// <returns>``0.</returns>
  383. private T GetRepository<T>(IEnumerable<T> repositories, string name)
  384. where T : class, IRepository
  385. {
  386. var enumerable = repositories as T[] ?? repositories.ToArray();
  387. return enumerable.FirstOrDefault(r => string.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase)) ??
  388. enumerable.FirstOrDefault();
  389. }
  390. /// <summary>
  391. /// Disposes the file system manager.
  392. /// </summary>
  393. private void DisposeFileSystemManager()
  394. {
  395. if (FileSystemManager != null)
  396. {
  397. FileSystemManager.Dispose();
  398. FileSystemManager = null;
  399. }
  400. }
  401. /// <summary>
  402. /// Reloads the file system manager.
  403. /// </summary>
  404. private void ReloadFileSystemManager()
  405. {
  406. DisposeFileSystemManager();
  407. FileSystemManager = new FileSystemManager(this, Logger, ApplicationHost.Resolve<ITaskManager>());
  408. FileSystemManager.StartWatchers();
  409. }
  410. /// <summary>
  411. /// Gets a User by Id
  412. /// </summary>
  413. /// <param name="id">The id.</param>
  414. /// <returns>User.</returns>
  415. /// <exception cref="System.ArgumentNullException"></exception>
  416. public User GetUserById(Guid id)
  417. {
  418. if (id == Guid.Empty)
  419. {
  420. throw new ArgumentNullException();
  421. }
  422. return Users.FirstOrDefault(u => u.Id == id);
  423. }
  424. /// <summary>
  425. /// Finds a library item by Id and UserId.
  426. /// </summary>
  427. /// <param name="id">The id.</param>
  428. /// <param name="userId">The user id.</param>
  429. /// <returns>BaseItem.</returns>
  430. /// <exception cref="System.ArgumentNullException">id</exception>
  431. public BaseItem GetItemById(Guid id, Guid userId)
  432. {
  433. if (id == Guid.Empty)
  434. {
  435. throw new ArgumentNullException("id");
  436. }
  437. if (userId == Guid.Empty)
  438. {
  439. throw new ArgumentNullException("userId");
  440. }
  441. var user = GetUserById(userId);
  442. var userRoot = user.RootFolder;
  443. return userRoot.FindItemById(id, user);
  444. }
  445. /// <summary>
  446. /// Gets the item by id.
  447. /// </summary>
  448. /// <param name="id">The id.</param>
  449. /// <returns>BaseItem.</returns>
  450. /// <exception cref="System.ArgumentNullException">id</exception>
  451. public BaseItem GetItemById(Guid id)
  452. {
  453. if (id == Guid.Empty)
  454. {
  455. throw new ArgumentNullException("id");
  456. }
  457. return RootFolder.FindItemById(id, null);
  458. }
  459. /// <summary>
  460. /// Completely overwrites the current configuration with a new copy
  461. /// </summary>
  462. /// <param name="config">The config.</param>
  463. public void UpdateConfiguration(ServerConfiguration config)
  464. {
  465. Configuration = config;
  466. SaveConfiguration();
  467. // Validate currently executing providers, in the background
  468. Task.Run(() =>
  469. {
  470. ProviderManager.ValidateCurrentlyRunningProviders();
  471. });
  472. }
  473. /// <summary>
  474. /// Removes the plugin.
  475. /// </summary>
  476. /// <param name="plugin">The plugin.</param>
  477. internal void RemovePlugin(IPlugin plugin)
  478. {
  479. var list = Plugins.ToList();
  480. list.Remove(plugin);
  481. Plugins = list;
  482. }
  483. /// <summary>
  484. /// Gets the system info.
  485. /// </summary>
  486. /// <returns>SystemInfo.</returns>
  487. public override SystemInfo GetSystemInfo()
  488. {
  489. var info = base.GetSystemInfo();
  490. if (InstallationManager != null)
  491. {
  492. info.InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToArray();
  493. info.CompletedInstallations = InstallationManager.CompletedInstallations.ToArray();
  494. }
  495. return info;
  496. }
  497. }
  498. }