LibraryManager.cs 38 KB

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