Kernel.cs 20 KB

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