Kernel.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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.Updates;
  16. using MediaBrowser.Controller.Weather;
  17. using MediaBrowser.Model.Configuration;
  18. using MediaBrowser.Model.Logging;
  19. using MediaBrowser.Model.Serialization;
  20. using MediaBrowser.Model.System;
  21. using System;
  22. using System.Collections.Generic;
  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, IServerApplicationPaths>
  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 Localized string files
  162. /// </summary>
  163. /// <value>The string files.</value>
  164. public IEnumerable<LocalizedStringData> StringFiles { get; private set; }
  165. /// <summary>
  166. /// Gets the list of plugin configuration pages
  167. /// </summary>
  168. /// <value>The configuration pages.</value>
  169. public IEnumerable<IPluginConfigurationPage> PluginConfigurationPages { get; private set; }
  170. /// <summary>
  171. /// Gets the intro providers.
  172. /// </summary>
  173. /// <value>The intro providers.</value>
  174. public IEnumerable<IIntroProvider> IntroProviders { get; private set; }
  175. /// <summary>
  176. /// Gets the list of currently registered weather prvoiders
  177. /// </summary>
  178. /// <value>The weather providers.</value>
  179. public IEnumerable<IWeatherProvider> WeatherProviders { get; private set; }
  180. /// <summary>
  181. /// Gets the list of currently registered metadata prvoiders
  182. /// </summary>
  183. /// <value>The metadata providers enumerable.</value>
  184. public BaseMetadataProvider[] MetadataProviders { get; private set; }
  185. /// <summary>
  186. /// Gets the list of currently registered image processors
  187. /// Image processors are specialized metadata providers that run after the normal ones
  188. /// </summary>
  189. /// <value>The image enhancers.</value>
  190. public IEnumerable<IImageEnhancer> 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. internal IEnumerable<IBaseItemResolver> EntityResolvers { get; private set; }
  196. /// <summary>
  197. /// Gets the list of BasePluginFolders added by plugins
  198. /// </summary>
  199. /// <value>The plugin folders.</value>
  200. internal IEnumerable<IVirtualFolderCreator> PluginFolderCreators { get; private set; }
  201. /// <summary>
  202. /// Gets the list of available user repositories
  203. /// </summary>
  204. /// <value>The user repositories.</value>
  205. private IEnumerable<IUserRepository> UserRepositories { get; set; }
  206. /// <summary>
  207. /// Gets the active user repository
  208. /// </summary>
  209. /// <value>The user repository.</value>
  210. public IUserRepository UserRepository { get; private set; }
  211. /// <summary>
  212. /// Gets the active user repository
  213. /// </summary>
  214. /// <value>The display preferences repository.</value>
  215. public IDisplayPreferencesRepository DisplayPreferencesRepository { get; private set; }
  216. /// <summary>
  217. /// Gets the list of available item repositories
  218. /// </summary>
  219. /// <value>The item repositories.</value>
  220. private IEnumerable<IItemRepository> ItemRepositories { get; set; }
  221. /// <summary>
  222. /// Gets the active item repository
  223. /// </summary>
  224. /// <value>The item repository.</value>
  225. public IItemRepository ItemRepository { get; private set; }
  226. /// <summary>
  227. /// Gets the list of available item repositories
  228. /// </summary>
  229. /// <value>The user data repositories.</value>
  230. private IEnumerable<IUserDataRepository> UserDataRepositories { get; set; }
  231. /// <summary>
  232. /// Gets the list of available DisplayPreferencesRepositories
  233. /// </summary>
  234. /// <value>The display preferences repositories.</value>
  235. private IEnumerable<IDisplayPreferencesRepository> DisplayPreferencesRepositories { get; set; }
  236. /// <summary>
  237. /// Gets the list of entity resolution ignore rules
  238. /// </summary>
  239. /// <value>The entity resolution ignore rules.</value>
  240. internal IEnumerable<IResolutionIgnoreRule> EntityResolutionIgnoreRules { get; private set; }
  241. /// <summary>
  242. /// Gets the active user data repository
  243. /// </summary>
  244. /// <value>The user data repository.</value>
  245. public IUserDataRepository UserDataRepository { get; private set; }
  246. /// <summary>
  247. /// Limits simultaneous access to various resources
  248. /// </summary>
  249. /// <value>The resource pools.</value>
  250. public ResourcePool ResourcePools { get; set; }
  251. /// <summary>
  252. /// Gets the UDP server port number.
  253. /// </summary>
  254. /// <value>The UDP server port number.</value>
  255. public override int UdpServerPortNumber
  256. {
  257. get { return 7359; }
  258. }
  259. /// <summary>
  260. /// Creates a kernel based on a Data path, which is akin to our current programdata path
  261. /// </summary>
  262. /// <param name="appHost">The app host.</param>
  263. /// <param name="appPaths">The app paths.</param>
  264. /// <param name="xmlSerializer">The XML serializer.</param>
  265. /// <param name="taskManager">The task manager.</param>
  266. /// <param name="logger">The logger.</param>
  267. /// <exception cref="System.ArgumentNullException">isoManager</exception>
  268. public Kernel(IApplicationHost appHost, IServerApplicationPaths appPaths, IXmlSerializer xmlSerializer, ILogger logger)
  269. : base(appHost, appPaths, xmlSerializer, logger)
  270. {
  271. Instance = this;
  272. // For now there's no real way to inject this properly
  273. BaseItem.Logger = logger;
  274. Ratings.Logger = logger;
  275. LocalizedStrings.Logger = logger;
  276. // For now, until this can become an interface
  277. BaseMetadataProvider.Logger = logger;
  278. }
  279. /// <summary>
  280. /// Composes the parts with ioc container.
  281. /// </summary>
  282. protected override void FindParts()
  283. {
  284. InstallationManager = (InstallationManager)ApplicationHost.CreateInstance(typeof(InstallationManager));
  285. FFMpegManager = (FFMpegManager)ApplicationHost.CreateInstance(typeof(FFMpegManager));
  286. LibraryManager = (LibraryManager)ApplicationHost.CreateInstance(typeof(LibraryManager));
  287. UserManager = (UserManager)ApplicationHost.CreateInstance(typeof(UserManager));
  288. ImageManager = (ImageManager)ApplicationHost.CreateInstance(typeof(ImageManager));
  289. ProviderManager = (ProviderManager)ApplicationHost.CreateInstance(typeof(ProviderManager));
  290. UserDataManager = (UserDataManager)ApplicationHost.CreateInstance(typeof(UserDataManager));
  291. PluginSecurityManager = (PluginSecurityManager)ApplicationHost.CreateInstance(typeof(PluginSecurityManager));
  292. base.FindParts();
  293. EntityResolutionIgnoreRules = ApplicationHost.GetExports<IResolutionIgnoreRule>();
  294. UserDataRepositories = ApplicationHost.GetExports<IUserDataRepository>();
  295. UserRepositories = ApplicationHost.GetExports<IUserRepository>();
  296. DisplayPreferencesRepositories = ApplicationHost.GetExports<IDisplayPreferencesRepository>();
  297. ItemRepositories = ApplicationHost.GetExports<IItemRepository>();
  298. WeatherProviders = ApplicationHost.GetExports<IWeatherProvider>();
  299. IntroProviders = ApplicationHost.GetExports<IIntroProvider>();
  300. PluginConfigurationPages = ApplicationHost.GetExports<IPluginConfigurationPage>();
  301. ImageEnhancers = ApplicationHost.GetExports<IImageEnhancer>().OrderBy(e => e.Priority).ToArray();
  302. PluginFolderCreators = ApplicationHost.GetExports<IVirtualFolderCreator>();
  303. StringFiles = ApplicationHost.GetExports<LocalizedStringData>();
  304. EntityResolvers = ApplicationHost.GetExports<IBaseItemResolver>().OrderBy(e => e.Priority).ToArray();
  305. MetadataProviders = ApplicationHost.GetExports<BaseMetadataProvider>().OrderBy(e => e.Priority).ToArray();
  306. }
  307. /// <summary>
  308. /// Performs initializations that can be reloaded at anytime
  309. /// </summary>
  310. /// <returns>Task.</returns>
  311. protected override async Task ReloadInternal()
  312. {
  313. // Reset these so that they can be lazy loaded again
  314. Users = null;
  315. RootFolder = null;
  316. await base.ReloadInternal().ConfigureAwait(false);
  317. ReloadResourcePools();
  318. ReloadFileSystemManager();
  319. await UserManager.RefreshUsersMetadata(CancellationToken.None).ConfigureAwait(false);
  320. }
  321. /// <summary>
  322. /// Releases unmanaged and - optionally - managed resources.
  323. /// </summary>
  324. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  325. protected override void Dispose(bool dispose)
  326. {
  327. if (dispose)
  328. {
  329. DisposeResourcePools();
  330. DisposeFileSystemManager();
  331. }
  332. base.Dispose(dispose);
  333. }
  334. /// <summary>
  335. /// Disposes the resource pools.
  336. /// </summary>
  337. private void DisposeResourcePools()
  338. {
  339. if (ResourcePools != null)
  340. {
  341. ResourcePools.Dispose();
  342. ResourcePools = null;
  343. }
  344. }
  345. /// <summary>
  346. /// Reloads the resource pools.
  347. /// </summary>
  348. private void ReloadResourcePools()
  349. {
  350. DisposeResourcePools();
  351. ResourcePools = new ResourcePool();
  352. }
  353. /// <summary>
  354. /// Called when [composable parts loaded].
  355. /// </summary>
  356. /// <returns>Task.</returns>
  357. protected override async Task OnComposablePartsLoaded()
  358. {
  359. // The base class will start up all the plugins
  360. await base.OnComposablePartsLoaded().ConfigureAwait(false);
  361. // Get the current item repository
  362. ItemRepository = GetRepository(ItemRepositories, Configuration.ItemRepository);
  363. var itemRepoTask = ItemRepository.Initialize();
  364. // Get the current user repository
  365. UserRepository = GetRepository(UserRepositories, Configuration.UserRepository);
  366. var userRepoTask = UserRepository.Initialize();
  367. // Get the current item repository
  368. UserDataRepository = GetRepository(UserDataRepositories, Configuration.UserDataRepository);
  369. var userDataRepoTask = UserDataRepository.Initialize();
  370. // Get the current display preferences repository
  371. DisplayPreferencesRepository = GetRepository(DisplayPreferencesRepositories, Configuration.DisplayPreferencesRepository);
  372. var displayPreferencesRepoTask = DisplayPreferencesRepository.Initialize();
  373. await Task.WhenAll(itemRepoTask, userRepoTask, userDataRepoTask, displayPreferencesRepoTask).ConfigureAwait(false);
  374. }
  375. /// <summary>
  376. /// Gets a repository by name from a list, and returns the default if not found
  377. /// </summary>
  378. /// <typeparam name="T"></typeparam>
  379. /// <param name="repositories">The repositories.</param>
  380. /// <param name="name">The name.</param>
  381. /// <returns>``0.</returns>
  382. private T GetRepository<T>(IEnumerable<T> repositories, string name)
  383. where T : class, IRepository
  384. {
  385. var enumerable = repositories as T[] ?? repositories.ToArray();
  386. return enumerable.FirstOrDefault(r => string.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase)) ??
  387. enumerable.FirstOrDefault();
  388. }
  389. /// <summary>
  390. /// Disposes the file system manager.
  391. /// </summary>
  392. private void DisposeFileSystemManager()
  393. {
  394. if (FileSystemManager != null)
  395. {
  396. FileSystemManager.Dispose();
  397. FileSystemManager = null;
  398. }
  399. }
  400. /// <summary>
  401. /// Reloads the file system manager.
  402. /// </summary>
  403. private void ReloadFileSystemManager()
  404. {
  405. DisposeFileSystemManager();
  406. FileSystemManager = new FileSystemManager(this, Logger, ApplicationHost.Resolve<ITaskManager>());
  407. FileSystemManager.StartWatchers();
  408. }
  409. /// <summary>
  410. /// Gets a User by Id
  411. /// </summary>
  412. /// <param name="id">The id.</param>
  413. /// <returns>User.</returns>
  414. /// <exception cref="System.ArgumentNullException"></exception>
  415. public User GetUserById(Guid id)
  416. {
  417. if (id == Guid.Empty)
  418. {
  419. throw new ArgumentNullException();
  420. }
  421. return Users.FirstOrDefault(u => u.Id == id);
  422. }
  423. /// <summary>
  424. /// Finds a library item by Id and UserId.
  425. /// </summary>
  426. /// <param name="id">The id.</param>
  427. /// <param name="userId">The user id.</param>
  428. /// <returns>BaseItem.</returns>
  429. /// <exception cref="System.ArgumentNullException">id</exception>
  430. public BaseItem GetItemById(Guid id, Guid userId)
  431. {
  432. if (id == Guid.Empty)
  433. {
  434. throw new ArgumentNullException("id");
  435. }
  436. if (userId == Guid.Empty)
  437. {
  438. throw new ArgumentNullException("userId");
  439. }
  440. var user = GetUserById(userId);
  441. var userRoot = user.RootFolder;
  442. return userRoot.FindItemById(id, user);
  443. }
  444. /// <summary>
  445. /// Gets the item by id.
  446. /// </summary>
  447. /// <param name="id">The id.</param>
  448. /// <returns>BaseItem.</returns>
  449. /// <exception cref="System.ArgumentNullException">id</exception>
  450. public BaseItem GetItemById(Guid id)
  451. {
  452. if (id == Guid.Empty)
  453. {
  454. throw new ArgumentNullException("id");
  455. }
  456. return RootFolder.FindItemById(id, null);
  457. }
  458. /// <summary>
  459. /// Completely overwrites the current configuration with a new copy
  460. /// </summary>
  461. /// <param name="config">The config.</param>
  462. public void UpdateConfiguration(ServerConfiguration config)
  463. {
  464. Configuration = config;
  465. SaveConfiguration();
  466. // Validate currently executing providers, in the background
  467. Task.Run(() =>
  468. {
  469. ProviderManager.ValidateCurrentlyRunningProviders();
  470. });
  471. }
  472. /// <summary>
  473. /// Removes the plugin.
  474. /// </summary>
  475. /// <param name="plugin">The plugin.</param>
  476. internal void RemovePlugin(IPlugin plugin)
  477. {
  478. var list = Plugins.ToList();
  479. list.Remove(plugin);
  480. Plugins = list;
  481. }
  482. /// <summary>
  483. /// Gets the system info.
  484. /// </summary>
  485. /// <returns>SystemInfo.</returns>
  486. public override SystemInfo GetSystemInfo()
  487. {
  488. var info = base.GetSystemInfo();
  489. if (InstallationManager != null)
  490. {
  491. info.InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToArray();
  492. info.CompletedInstallations = InstallationManager.CompletedInstallations.ToArray();
  493. }
  494. return info;
  495. }
  496. }
  497. }