LibraryManager.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.ScheduledTasks;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Entities.Movies;
  8. using MediaBrowser.Controller.IO;
  9. using MediaBrowser.Controller.Library;
  10. using MediaBrowser.Controller.Resolvers;
  11. using MediaBrowser.Controller.Sorting;
  12. using MediaBrowser.Model.Configuration;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.Logging;
  15. using MediaBrowser.Server.Implementations.ScheduledTasks;
  16. using MoreLinq;
  17. using System;
  18. using System.Collections.Concurrent;
  19. using System.Collections.Generic;
  20. using System.Globalization;
  21. using System.IO;
  22. using System.Linq;
  23. using System.Threading;
  24. using System.Threading.Tasks;
  25. using SortOrder = MediaBrowser.Model.Entities.SortOrder;
  26. namespace MediaBrowser.Server.Implementations.Library
  27. {
  28. /// <summary>
  29. /// Class LibraryManager
  30. /// </summary>
  31. public class LibraryManager : ILibraryManager
  32. {
  33. /// <summary>
  34. /// Gets the intro providers.
  35. /// </summary>
  36. /// <value>The intro providers.</value>
  37. private IEnumerable<IIntroProvider> IntroProviders { get; set; }
  38. /// <summary>
  39. /// Gets the list of entity resolution ignore rules
  40. /// </summary>
  41. /// <value>The entity resolution ignore rules.</value>
  42. private IEnumerable<IResolverIgnoreRule> EntityResolutionIgnoreRules { get; set; }
  43. /// <summary>
  44. /// Gets the list of BasePluginFolders added by plugins
  45. /// </summary>
  46. /// <value>The plugin folders.</value>
  47. private IEnumerable<IVirtualFolderCreator> PluginFolderCreators { get; set; }
  48. /// <summary>
  49. /// Gets the list of currently registered entity resolvers
  50. /// </summary>
  51. /// <value>The entity resolvers enumerable.</value>
  52. private IEnumerable<IItemResolver> EntityResolvers { get; set; }
  53. /// <summary>
  54. /// Gets or sets the comparers.
  55. /// </summary>
  56. /// <value>The comparers.</value>
  57. private IEnumerable<IBaseItemComparer> Comparers { get; set; }
  58. #region LibraryChanged Event
  59. /// <summary>
  60. /// Fires whenever any validation routine adds or removes items. The added and removed items are properties of the args.
  61. /// *** Will fire asynchronously. ***
  62. /// </summary>
  63. public event EventHandler<ChildrenChangedEventArgs> LibraryChanged;
  64. /// <summary>
  65. /// Raises the <see cref="E:LibraryChanged" /> event.
  66. /// </summary>
  67. /// <param name="args">The <see cref="ChildrenChangedEventArgs" /> instance containing the event data.</param>
  68. public void ReportLibraryChanged(ChildrenChangedEventArgs args)
  69. {
  70. UpdateLibraryCache(args);
  71. EventHelper.QueueEventIfNotNull(LibraryChanged, this, args, _logger);
  72. }
  73. #endregion
  74. /// <summary>
  75. /// The _logger
  76. /// </summary>
  77. private readonly ILogger _logger;
  78. /// <summary>
  79. /// The _task manager
  80. /// </summary>
  81. private readonly ITaskManager _taskManager;
  82. /// <summary>
  83. /// The _user manager
  84. /// </summary>
  85. private readonly IUserManager _userManager;
  86. /// <summary>
  87. /// Gets or sets the kernel.
  88. /// </summary>
  89. /// <value>The kernel.</value>
  90. private Kernel Kernel { get; set; }
  91. /// <summary>
  92. /// Gets or sets the configuration manager.
  93. /// </summary>
  94. /// <value>The configuration manager.</value>
  95. private IServerConfigurationManager ConfigurationManager { get; set; }
  96. /// <summary>
  97. /// A collection of items that may be referenced from multiple physical places in the library
  98. /// (typically, multiple user roots). We store them here and be sure they all reference a
  99. /// single instance.
  100. /// </summary>
  101. private ConcurrentDictionary<Guid, BaseItem> ByReferenceItems { get; set; }
  102. private ConcurrentDictionary<Guid, BaseItem> _libraryItemsCache;
  103. private object _libraryItemsCacheSyncLock = new object();
  104. private bool _libraryItemsCacheInitialized;
  105. private ConcurrentDictionary<Guid, BaseItem> LibraryItemsCache
  106. {
  107. get
  108. {
  109. LazyInitializer.EnsureInitialized(ref _libraryItemsCache, ref _libraryItemsCacheInitialized, ref _libraryItemsCacheSyncLock, CreateLibraryItemsCache);
  110. return _libraryItemsCache;
  111. }
  112. }
  113. private ConcurrentDictionary<string, UserRootFolder> _userRootFolders =
  114. new ConcurrentDictionary<string, UserRootFolder>();
  115. /// <summary>
  116. /// Initializes a new instance of the <see cref="LibraryManager" /> class.
  117. /// </summary>
  118. /// <param name="kernel">The kernel.</param>
  119. /// <param name="logger">The logger.</param>
  120. /// <param name="taskManager">The task manager.</param>
  121. /// <param name="userManager">The user manager.</param>
  122. /// <param name="configurationManager">The configuration manager.</param>
  123. public LibraryManager(Kernel kernel, ILogger logger, ITaskManager taskManager, IUserManager userManager, IServerConfigurationManager configurationManager)
  124. {
  125. Kernel = kernel;
  126. _logger = logger;
  127. _taskManager = taskManager;
  128. _userManager = userManager;
  129. ConfigurationManager = configurationManager;
  130. ByReferenceItems = new ConcurrentDictionary<Guid, BaseItem>();
  131. ConfigurationManager.ConfigurationUpdated += kernel_ConfigurationUpdated;
  132. RecordConfigurationValues(configurationManager.Configuration);
  133. }
  134. /// <summary>
  135. /// Adds the parts.
  136. /// </summary>
  137. /// <param name="rules">The rules.</param>
  138. /// <param name="pluginFolders">The plugin folders.</param>
  139. /// <param name="resolvers">The resolvers.</param>
  140. /// <param name="introProviders">The intro providers.</param>
  141. /// <param name="itemComparers">The item comparers.</param>
  142. public void AddParts(IEnumerable<IResolverIgnoreRule> rules, IEnumerable<IVirtualFolderCreator> pluginFolders, IEnumerable<IItemResolver> resolvers, IEnumerable<IIntroProvider> introProviders, IEnumerable<IBaseItemComparer> itemComparers)
  143. {
  144. EntityResolutionIgnoreRules = rules;
  145. PluginFolderCreators = pluginFolders;
  146. EntityResolvers = resolvers.OrderBy(i => i.Priority).ToArray();
  147. IntroProviders = introProviders;
  148. Comparers = itemComparers;
  149. }
  150. /// <summary>
  151. /// The _root folder
  152. /// </summary>
  153. private AggregateFolder _rootFolder;
  154. /// <summary>
  155. /// The _root folder sync lock
  156. /// </summary>
  157. private object _rootFolderSyncLock = new object();
  158. /// <summary>
  159. /// The _root folder initialized
  160. /// </summary>
  161. private bool _rootFolderInitialized;
  162. /// <summary>
  163. /// Gets the root folder.
  164. /// </summary>
  165. /// <value>The root folder.</value>
  166. public AggregateFolder RootFolder
  167. {
  168. get
  169. {
  170. LazyInitializer.EnsureInitialized(ref _rootFolder, ref _rootFolderInitialized, ref _rootFolderSyncLock, CreateRootFolder);
  171. return _rootFolder;
  172. }
  173. private set
  174. {
  175. _rootFolder = value;
  176. if (value == null)
  177. {
  178. _rootFolderInitialized = false;
  179. }
  180. }
  181. }
  182. private bool _internetProvidersEnabled;
  183. private bool _peopleImageFetchingEnabled;
  184. private void RecordConfigurationValues(ServerConfiguration configuration)
  185. {
  186. _internetProvidersEnabled = configuration.EnableInternetProviders;
  187. _peopleImageFetchingEnabled = configuration.InternetProviderExcludeTypes == null || !configuration.InternetProviderExcludeTypes.Contains(typeof(Person).Name, StringComparer.OrdinalIgnoreCase);
  188. }
  189. /// <summary>
  190. /// Handles the ConfigurationUpdated event of the kernel control.
  191. /// </summary>
  192. /// <param name="sender">The source of the event.</param>
  193. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  194. void kernel_ConfigurationUpdated(object sender, EventArgs e)
  195. {
  196. var config = ConfigurationManager.Configuration;
  197. // Figure out whether or not we should refresh people after the update is finished
  198. var refreshPeopleAfterUpdate = !_internetProvidersEnabled && config.EnableInternetProviders;
  199. // This is true if internet providers has just been turned on, or if People have just been removed from InternetProviderExcludeTypes
  200. if (!refreshPeopleAfterUpdate)
  201. {
  202. var newConfigurationFetchesPeopleImages = config.InternetProviderExcludeTypes == null || !config.InternetProviderExcludeTypes.Contains(typeof(Person).Name, StringComparer.OrdinalIgnoreCase);
  203. refreshPeopleAfterUpdate = newConfigurationFetchesPeopleImages && !_peopleImageFetchingEnabled;
  204. }
  205. RecordConfigurationValues(config);
  206. Task.Run(() =>
  207. {
  208. // Any number of configuration settings could change the way the library is refreshed, so do that now
  209. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  210. if (refreshPeopleAfterUpdate)
  211. {
  212. _taskManager.CancelIfRunningAndQueue<PeopleValidationTask>();
  213. }
  214. });
  215. }
  216. /// <summary>
  217. /// Creates the library items cache.
  218. /// </summary>
  219. /// <returns>ConcurrentDictionary{GuidBaseItem}.</returns>
  220. private ConcurrentDictionary<Guid, BaseItem> CreateLibraryItemsCache()
  221. {
  222. var items = RootFolder.RecursiveChildren.ToList();
  223. items.Add(RootFolder);
  224. var specialFeatures = items.OfType<Movie>().SelectMany(i => i.SpecialFeatures).ToList();
  225. var localTrailers = items.SelectMany(i => i.LocalTrailers).ToList();
  226. items.AddRange(specialFeatures);
  227. items.AddRange(localTrailers);
  228. // Need to use DistinctBy Id because there could be multiple instances with the same id
  229. // due to sharing the default library
  230. var userRootFolders = _userManager.Users.Select(i => i.RootFolder)
  231. .DistinctBy(i => i.Id)
  232. .ToList();
  233. items.AddRange(userRootFolders);
  234. // Get all user collection folders
  235. var userFolders =
  236. _userManager.Users.SelectMany(i => i.RootFolder.Children)
  237. .Where(i => !(i is BasePluginFolder))
  238. .DistinctBy(i => i.Id)
  239. .ToList();
  240. items.AddRange(userFolders);
  241. return new ConcurrentDictionary<Guid,BaseItem>(items.ToDictionary(i => i.Id));
  242. }
  243. /// <summary>
  244. /// Updates the library cache.
  245. /// </summary>
  246. /// <param name="args">The <see cref="ChildrenChangedEventArgs"/> instance containing the event data.</param>
  247. private void UpdateLibraryCache(ChildrenChangedEventArgs args)
  248. {
  249. UpdateItemInLibraryCache(args.Folder);
  250. foreach (var item in args.ItemsAdded)
  251. {
  252. UpdateItemInLibraryCache(item);
  253. }
  254. foreach (var item in args.ItemsUpdated)
  255. {
  256. UpdateItemInLibraryCache(item);
  257. }
  258. }
  259. /// <summary>
  260. /// Updates the item in library cache.
  261. /// </summary>
  262. /// <param name="item">The item.</param>
  263. private void UpdateItemInLibraryCache(BaseItem item)
  264. {
  265. LibraryItemsCache.AddOrUpdate(item.Id, item, delegate { return item; });
  266. foreach (var trailer in item.LocalTrailers)
  267. {
  268. // Prevent access to foreach variable in closure
  269. var trailer1 = trailer;
  270. LibraryItemsCache.AddOrUpdate(trailer.Id, trailer, delegate { return trailer1; });
  271. }
  272. var movie = item as Movie;
  273. if (movie != null)
  274. {
  275. foreach (var special in movie.SpecialFeatures)
  276. {
  277. // Prevent access to foreach variable in closure
  278. var special1 = special;
  279. LibraryItemsCache.AddOrUpdate(special.Id, special, delegate { return special1; });
  280. }
  281. }
  282. }
  283. /// <summary>
  284. /// Resolves the item.
  285. /// </summary>
  286. /// <param name="args">The args.</param>
  287. /// <returns>BaseItem.</returns>
  288. public BaseItem ResolveItem(ItemResolveArgs args)
  289. {
  290. var item = EntityResolvers.Select(r => r.ResolvePath(args)).FirstOrDefault(i => i != null);
  291. if (item != null)
  292. {
  293. ResolverHelper.SetInitialItemValues(item, args);
  294. // Now handle the issue with posibly having the same item referenced from multiple physical
  295. // places within the library. Be sure we always end up with just one instance.
  296. if (item is IByReferenceItem)
  297. {
  298. item = GetOrAddByReferenceItem(item);
  299. }
  300. }
  301. return item;
  302. }
  303. /// <summary>
  304. /// Ensure supplied item has only one instance throughout
  305. /// </summary>
  306. /// <param name="item"></param>
  307. /// <returns>The proper instance to the item</returns>
  308. public BaseItem GetOrAddByReferenceItem(BaseItem item)
  309. {
  310. // Add this item to our list if not there already
  311. if (!ByReferenceItems.TryAdd(item.Id, item))
  312. {
  313. // Already there - return the existing reference
  314. item = ByReferenceItems[item.Id];
  315. }
  316. return item;
  317. }
  318. /// <summary>
  319. /// Resolves a path into a BaseItem
  320. /// </summary>
  321. /// <param name="path">The path.</param>
  322. /// <param name="parent">The parent.</param>
  323. /// <param name="fileInfo">The file info.</param>
  324. /// <returns>BaseItem.</returns>
  325. /// <exception cref="System.ArgumentNullException"></exception>
  326. public BaseItem ResolvePath(string path, Folder parent = null, WIN32_FIND_DATA? fileInfo = null)
  327. {
  328. if (string.IsNullOrEmpty(path))
  329. {
  330. throw new ArgumentNullException();
  331. }
  332. fileInfo = fileInfo ?? FileSystem.GetFileData(path);
  333. if (!fileInfo.HasValue)
  334. {
  335. return null;
  336. }
  337. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths)
  338. {
  339. Parent = parent,
  340. Path = path,
  341. FileInfo = fileInfo.Value
  342. };
  343. // Return null if ignore rules deem that we should do so
  344. if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(args)))
  345. {
  346. return null;
  347. }
  348. // Gather child folder and files
  349. if (args.IsDirectory)
  350. {
  351. // When resolving the root, we need it's grandchildren (children of user views)
  352. var flattenFolderDepth = args.IsPhysicalRoot ? 2 : 0;
  353. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, _logger, flattenFolderDepth: flattenFolderDepth, args: args);
  354. }
  355. // Check to see if we should resolve based on our contents
  356. if (args.IsDirectory && !ShouldResolvePathContents(args))
  357. {
  358. return null;
  359. }
  360. return ResolveItem(args);
  361. }
  362. /// <summary>
  363. /// Determines whether a path should be ignored based on its contents - called after the contents have been read
  364. /// </summary>
  365. /// <param name="args">The args.</param>
  366. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  367. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  368. {
  369. // Ignore any folders containing a file called .ignore
  370. return !args.ContainsFileSystemEntryByName(".ignore");
  371. }
  372. /// <summary>
  373. /// Resolves a set of files into a list of BaseItem
  374. /// </summary>
  375. /// <typeparam name="T"></typeparam>
  376. /// <param name="files">The files.</param>
  377. /// <param name="parent">The parent.</param>
  378. /// <returns>List{``0}.</returns>
  379. public List<T> ResolvePaths<T>(IEnumerable<WIN32_FIND_DATA> files, Folder parent)
  380. where T : BaseItem
  381. {
  382. var list = new List<T>();
  383. Parallel.ForEach(files, f =>
  384. {
  385. try
  386. {
  387. var item = ResolvePath(f.Path, parent, f) as T;
  388. if (item != null)
  389. {
  390. lock (list)
  391. {
  392. list.Add(item);
  393. }
  394. }
  395. }
  396. catch (Exception ex)
  397. {
  398. _logger.ErrorException("Error resolving path {0}", ex, f.Path);
  399. }
  400. });
  401. return list;
  402. }
  403. /// <summary>
  404. /// Creates the root media folder
  405. /// </summary>
  406. /// <returns>AggregateFolder.</returns>
  407. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  408. public AggregateFolder CreateRootFolder()
  409. {
  410. var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
  411. var rootFolder = Kernel.ItemRepository.RetrieveItem(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(rootFolderPath);
  412. // Add in the plug-in folders
  413. foreach (var child in PluginFolderCreators)
  414. {
  415. rootFolder.AddVirtualChild(child.GetFolder());
  416. }
  417. return rootFolder;
  418. }
  419. /// <summary>
  420. /// Gets the user root folder.
  421. /// </summary>
  422. /// <param name="userRootPath">The user root path.</param>
  423. /// <returns>UserRootFolder.</returns>
  424. public UserRootFolder GetUserRootFolder(string userRootPath)
  425. {
  426. return _userRootFolders.GetOrAdd(userRootPath, key => Kernel.ItemRepository.RetrieveItem(userRootPath.GetMBId(typeof(UserRootFolder))) as UserRootFolder ?? (UserRootFolder)ResolvePath(userRootPath));
  427. }
  428. /// <summary>
  429. /// Gets a Person
  430. /// </summary>
  431. /// <param name="name">The name.</param>
  432. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  433. /// <returns>Task{Person}.</returns>
  434. public Task<Person> GetPerson(string name, bool allowSlowProviders = false)
  435. {
  436. return GetPerson(name, CancellationToken.None, allowSlowProviders);
  437. }
  438. /// <summary>
  439. /// Gets a Person
  440. /// </summary>
  441. /// <param name="name">The name.</param>
  442. /// <param name="cancellationToken">The cancellation token.</param>
  443. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  444. /// <returns>Task{Person}.</returns>
  445. private Task<Person> GetPerson(string name, CancellationToken cancellationToken, bool allowSlowProviders = false)
  446. {
  447. return GetImagesByNameItem<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name, cancellationToken, allowSlowProviders);
  448. }
  449. /// <summary>
  450. /// Gets a Studio
  451. /// </summary>
  452. /// <param name="name">The name.</param>
  453. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  454. /// <returns>Task{Studio}.</returns>
  455. public Task<Studio> GetStudio(string name, bool allowSlowProviders = false)
  456. {
  457. return GetImagesByNameItem<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name, CancellationToken.None, allowSlowProviders);
  458. }
  459. /// <summary>
  460. /// Gets a Genre
  461. /// </summary>
  462. /// <param name="name">The name.</param>
  463. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  464. /// <returns>Task{Genre}.</returns>
  465. public Task<Genre> GetGenre(string name, bool allowSlowProviders = false)
  466. {
  467. return GetImagesByNameItem<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name, CancellationToken.None, allowSlowProviders);
  468. }
  469. /// <summary>
  470. /// The us culture
  471. /// </summary>
  472. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  473. /// <summary>
  474. /// Gets a Year
  475. /// </summary>
  476. /// <param name="value">The value.</param>
  477. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  478. /// <returns>Task{Year}.</returns>
  479. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  480. public Task<Year> GetYear(int value, bool allowSlowProviders = false)
  481. {
  482. if (value <= 0)
  483. {
  484. throw new ArgumentOutOfRangeException();
  485. }
  486. return GetImagesByNameItem<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture), CancellationToken.None, allowSlowProviders);
  487. }
  488. /// <summary>
  489. /// The images by name item cache
  490. /// </summary>
  491. private readonly ConcurrentDictionary<string, object> ImagesByNameItemCache = new ConcurrentDictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  492. /// <summary>
  493. /// Generically retrieves an IBN item
  494. /// </summary>
  495. /// <typeparam name="T"></typeparam>
  496. /// <param name="path">The path.</param>
  497. /// <param name="name">The name.</param>
  498. /// <param name="cancellationToken">The cancellation token.</param>
  499. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  500. /// <returns>Task{``0}.</returns>
  501. /// <exception cref="System.ArgumentNullException"></exception>
  502. private Task<T> GetImagesByNameItem<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  503. where T : BaseItem, new()
  504. {
  505. if (string.IsNullOrEmpty(path))
  506. {
  507. throw new ArgumentNullException();
  508. }
  509. if (string.IsNullOrEmpty(name))
  510. {
  511. throw new ArgumentNullException();
  512. }
  513. var key = Path.Combine(path, FileSystem.GetValidFilename(name));
  514. var obj = ImagesByNameItemCache.GetOrAdd(key, keyname => CreateImagesByNameItem<T>(path, name, cancellationToken, allowSlowProviders));
  515. return obj as Task<T>;
  516. }
  517. /// <summary>
  518. /// Creates an IBN item based on a given path
  519. /// </summary>
  520. /// <typeparam name="T"></typeparam>
  521. /// <param name="path">The path.</param>
  522. /// <param name="name">The name.</param>
  523. /// <param name="cancellationToken">The cancellation token.</param>
  524. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  525. /// <returns>Task{``0}.</returns>
  526. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  527. private async Task<T> CreateImagesByNameItem<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  528. where T : BaseItem, new()
  529. {
  530. cancellationToken.ThrowIfCancellationRequested();
  531. _logger.Debug("Creating {0}: {1}", typeof(T).Name, name);
  532. path = Path.Combine(path, FileSystem.GetValidFilename(name));
  533. var fileInfo = FileSystem.GetFileData(path);
  534. var isNew = false;
  535. if (!fileInfo.HasValue)
  536. {
  537. Directory.CreateDirectory(path);
  538. fileInfo = FileSystem.GetFileData(path);
  539. if (!fileInfo.HasValue)
  540. {
  541. throw new IOException("Path not created: " + path);
  542. }
  543. isNew = true;
  544. }
  545. cancellationToken.ThrowIfCancellationRequested();
  546. var id = path.GetMBId(typeof(T));
  547. var item = Kernel.ItemRepository.RetrieveItem(id) as T;
  548. if (item == null)
  549. {
  550. item = new T
  551. {
  552. Name = name,
  553. Id = id,
  554. DateCreated = fileInfo.Value.CreationTimeUtc,
  555. DateModified = fileInfo.Value.LastWriteTimeUtc,
  556. Path = path
  557. };
  558. isNew = true;
  559. }
  560. cancellationToken.ThrowIfCancellationRequested();
  561. // Set this now so we don't cause additional file system access during provider executions
  562. item.ResetResolveArgs(fileInfo);
  563. await item.RefreshMetadata(cancellationToken, isNew, allowSlowProviders: allowSlowProviders).ConfigureAwait(false);
  564. cancellationToken.ThrowIfCancellationRequested();
  565. return item;
  566. }
  567. /// <summary>
  568. /// Validate and refresh the People sub-set of the IBN.
  569. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  570. /// </summary>
  571. /// <param name="cancellationToken">The cancellation token.</param>
  572. /// <param name="progress">The progress.</param>
  573. /// <returns>Task.</returns>
  574. public async Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  575. {
  576. // Clear the IBN cache
  577. ImagesByNameItemCache.Clear();
  578. const int maxTasks = 250;
  579. var tasks = new List<Task>();
  580. var includedPersonTypes = new[] { PersonType.Actor, PersonType.Director };
  581. var people = RootFolder.RecursiveChildren
  582. .Where(c => c.People != null)
  583. .SelectMany(c => c.People.Where(p => includedPersonTypes.Contains(p.Type)))
  584. .DistinctBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
  585. .ToList();
  586. var numComplete = 0;
  587. foreach (var person in people)
  588. {
  589. if (tasks.Count > maxTasks)
  590. {
  591. await Task.WhenAll(tasks).ConfigureAwait(false);
  592. tasks.Clear();
  593. // Safe cancellation point, when there are no pending tasks
  594. cancellationToken.ThrowIfCancellationRequested();
  595. }
  596. // Avoid accessing the foreach variable within the closure
  597. var currentPerson = person;
  598. tasks.Add(Task.Run(async () =>
  599. {
  600. cancellationToken.ThrowIfCancellationRequested();
  601. try
  602. {
  603. await GetPerson(currentPerson.Name, cancellationToken, allowSlowProviders: true).ConfigureAwait(false);
  604. }
  605. catch (IOException ex)
  606. {
  607. _logger.ErrorException("Error validating IBN entry {0}", ex, currentPerson.Name);
  608. }
  609. // Update progress
  610. lock (progress)
  611. {
  612. numComplete++;
  613. double percent = numComplete;
  614. percent /= people.Count;
  615. progress.Report(100 * percent);
  616. }
  617. }));
  618. }
  619. await Task.WhenAll(tasks).ConfigureAwait(false);
  620. progress.Report(100);
  621. _logger.Info("People validation complete");
  622. }
  623. /// <summary>
  624. /// Reloads the root media folder
  625. /// </summary>
  626. /// <param name="progress">The progress.</param>
  627. /// <param name="cancellationToken">The cancellation token.</param>
  628. /// <returns>Task.</returns>
  629. public async Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  630. {
  631. _logger.Info("Validating media library");
  632. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  633. // Start by just validating the children of the root, but go no further
  634. await RootFolder.ValidateChildren(new Progress<double> { }, cancellationToken, recursive: false);
  635. foreach (var folder in _userManager.Users.Select(u => u.RootFolder).Distinct())
  636. {
  637. await ValidateCollectionFolders(folder, cancellationToken).ConfigureAwait(false);
  638. }
  639. // Now validate the entire media library
  640. await RootFolder.ValidateChildren(progress, cancellationToken, recursive: true).ConfigureAwait(false);
  641. }
  642. /// <summary>
  643. /// Validates only the collection folders for a User and goes no further
  644. /// </summary>
  645. /// <param name="userRootFolder">The user root folder.</param>
  646. /// <param name="cancellationToken">The cancellation token.</param>
  647. /// <returns>Task.</returns>
  648. private async Task ValidateCollectionFolders(UserRootFolder userRootFolder, CancellationToken cancellationToken)
  649. {
  650. _logger.Info("Validating collection folders within {0}", userRootFolder.Path);
  651. await userRootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  652. cancellationToken.ThrowIfCancellationRequested();
  653. await userRootFolder.ValidateChildren(new Progress<double> { }, cancellationToken, recursive: false).ConfigureAwait(false);
  654. }
  655. /// <summary>
  656. /// Gets the default view.
  657. /// </summary>
  658. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  659. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  660. {
  661. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  662. }
  663. /// <summary>
  664. /// Gets the view.
  665. /// </summary>
  666. /// <param name="user">The user.</param>
  667. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  668. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  669. {
  670. return GetView(user.RootFolderPath);
  671. }
  672. /// <summary>
  673. /// Gets the view.
  674. /// </summary>
  675. /// <param name="path">The path.</param>
  676. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  677. private IEnumerable<VirtualFolderInfo> GetView(string path)
  678. {
  679. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  680. .Select(dir => new VirtualFolderInfo
  681. {
  682. Name = Path.GetFileName(dir),
  683. Locations = Directory.EnumerateFiles(dir, "*.lnk", SearchOption.TopDirectoryOnly).Select(FileSystem.ResolveShortcut).ToList()
  684. });
  685. }
  686. /// <summary>
  687. /// Gets the item by id.
  688. /// </summary>
  689. /// <param name="id">The id.</param>
  690. /// <returns>BaseItem.</returns>
  691. /// <exception cref="System.ArgumentNullException">id</exception>
  692. public BaseItem GetItemById(Guid id)
  693. {
  694. if (id == Guid.Empty)
  695. {
  696. throw new ArgumentNullException("id");
  697. }
  698. BaseItem item;
  699. LibraryItemsCache.TryGetValue(id, out item);
  700. return item;
  701. }
  702. /// <summary>
  703. /// Gets the intros.
  704. /// </summary>
  705. /// <param name="item">The item.</param>
  706. /// <param name="user">The user.</param>
  707. /// <returns>IEnumerable{System.String}.</returns>
  708. public IEnumerable<string> GetIntros(BaseItem item, User user)
  709. {
  710. return IntroProviders.SelectMany(i => i.GetIntros(item, user));
  711. }
  712. /// <summary>
  713. /// Sorts the specified sort by.
  714. /// </summary>
  715. /// <param name="items">The items.</param>
  716. /// <param name="user">The user.</param>
  717. /// <param name="sortBy">The sort by.</param>
  718. /// <param name="sortOrder">The sort order.</param>
  719. /// <returns>IEnumerable{BaseItem}.</returns>
  720. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  721. {
  722. var isFirst = true;
  723. IOrderedEnumerable<BaseItem> orderedItems = null;
  724. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  725. {
  726. if (isFirst)
  727. {
  728. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  729. }
  730. else
  731. {
  732. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  733. }
  734. isFirst = false;
  735. }
  736. return orderedItems ?? items;
  737. }
  738. /// <summary>
  739. /// Gets the comparer.
  740. /// </summary>
  741. /// <param name="name">The name.</param>
  742. /// <param name="user">The user.</param>
  743. /// <returns>IBaseItemComparer.</returns>
  744. private IBaseItemComparer GetComparer(string name, User user)
  745. {
  746. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  747. if (comparer != null)
  748. {
  749. // If it requires a user, create a new one, and assign the user
  750. if (comparer is IUserBaseItemComparer)
  751. {
  752. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  753. userComparer.User = user;
  754. userComparer.UserManager = _userManager;
  755. return userComparer;
  756. }
  757. }
  758. return comparer;
  759. }
  760. }
  761. }