LibraryManager.cs 36 KB

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