LibraryManager.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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. /// <returns>Task{Person}.</returns>
  447. private Task<Person> GetPerson(string name, CancellationToken cancellationToken, bool allowSlowProviders = false)
  448. {
  449. return GetImagesByNameItem<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name, cancellationToken, allowSlowProviders);
  450. }
  451. /// <summary>
  452. /// Gets a Studio
  453. /// </summary>
  454. /// <param name="name">The name.</param>
  455. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  456. /// <returns>Task{Studio}.</returns>
  457. public Task<Studio> GetStudio(string name, bool allowSlowProviders = false)
  458. {
  459. return GetImagesByNameItem<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name, CancellationToken.None, allowSlowProviders);
  460. }
  461. /// <summary>
  462. /// Gets a Genre
  463. /// </summary>
  464. /// <param name="name">The name.</param>
  465. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  466. /// <returns>Task{Genre}.</returns>
  467. public Task<Genre> GetGenre(string name, bool allowSlowProviders = false)
  468. {
  469. return GetImagesByNameItem<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name, CancellationToken.None, allowSlowProviders);
  470. }
  471. /// <summary>
  472. /// The us culture
  473. /// </summary>
  474. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  475. /// <summary>
  476. /// Gets a Year
  477. /// </summary>
  478. /// <param name="value">The value.</param>
  479. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  480. /// <returns>Task{Year}.</returns>
  481. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  482. public Task<Year> GetYear(int value, bool allowSlowProviders = false)
  483. {
  484. if (value <= 0)
  485. {
  486. throw new ArgumentOutOfRangeException();
  487. }
  488. return GetImagesByNameItem<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture), CancellationToken.None, allowSlowProviders);
  489. }
  490. /// <summary>
  491. /// The images by name item cache
  492. /// </summary>
  493. private readonly ConcurrentDictionary<string, object> ImagesByNameItemCache = new ConcurrentDictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  494. /// <summary>
  495. /// Generically retrieves an IBN item
  496. /// </summary>
  497. /// <typeparam name="T"></typeparam>
  498. /// <param name="path">The path.</param>
  499. /// <param name="name">The name.</param>
  500. /// <param name="cancellationToken">The cancellation token.</param>
  501. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  502. /// <returns>Task{``0}.</returns>
  503. /// <exception cref="System.ArgumentNullException"></exception>
  504. private Task<T> GetImagesByNameItem<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  505. where T : BaseItem, new()
  506. {
  507. if (string.IsNullOrEmpty(path))
  508. {
  509. throw new ArgumentNullException();
  510. }
  511. if (string.IsNullOrEmpty(name))
  512. {
  513. throw new ArgumentNullException();
  514. }
  515. var key = Path.Combine(path, FileSystem.GetValidFilename(name));
  516. var obj = ImagesByNameItemCache.GetOrAdd(key, keyname => CreateImagesByNameItem<T>(path, name, cancellationToken, allowSlowProviders));
  517. return obj as Task<T>;
  518. }
  519. /// <summary>
  520. /// Creates an IBN item based on a given path
  521. /// </summary>
  522. /// <typeparam name="T"></typeparam>
  523. /// <param name="path">The path.</param>
  524. /// <param name="name">The name.</param>
  525. /// <param name="cancellationToken">The cancellation token.</param>
  526. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  527. /// <returns>Task{``0}.</returns>
  528. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  529. private async Task<T> CreateImagesByNameItem<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  530. where T : BaseItem, new()
  531. {
  532. cancellationToken.ThrowIfCancellationRequested();
  533. _logger.Debug("Creating {0}: {1}", typeof(T).Name, name);
  534. path = Path.Combine(path, FileSystem.GetValidFilename(name));
  535. var fileInfo = FileSystem.GetFileData(path);
  536. var isNew = false;
  537. if (!fileInfo.HasValue)
  538. {
  539. Directory.CreateDirectory(path);
  540. fileInfo = FileSystem.GetFileData(path);
  541. if (!fileInfo.HasValue)
  542. {
  543. throw new IOException("Path not created: " + path);
  544. }
  545. isNew = true;
  546. }
  547. cancellationToken.ThrowIfCancellationRequested();
  548. var id = path.GetMBId(typeof(T));
  549. var item = RetrieveItem(id) as T;
  550. if (item == null)
  551. {
  552. item = new T
  553. {
  554. Name = name,
  555. Id = id,
  556. DateCreated = fileInfo.Value.CreationTimeUtc,
  557. DateModified = fileInfo.Value.LastWriteTimeUtc,
  558. Path = path
  559. };
  560. isNew = true;
  561. }
  562. cancellationToken.ThrowIfCancellationRequested();
  563. // Set this now so we don't cause additional file system access during provider executions
  564. item.ResetResolveArgs(fileInfo);
  565. await item.RefreshMetadata(cancellationToken, isNew, allowSlowProviders: allowSlowProviders).ConfigureAwait(false);
  566. cancellationToken.ThrowIfCancellationRequested();
  567. return item;
  568. }
  569. /// <summary>
  570. /// Validate and refresh the People sub-set of the IBN.
  571. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  572. /// </summary>
  573. /// <param name="cancellationToken">The cancellation token.</param>
  574. /// <param name="progress">The progress.</param>
  575. /// <returns>Task.</returns>
  576. public async Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  577. {
  578. // Clear the IBN cache
  579. ImagesByNameItemCache.Clear();
  580. const int maxTasks = 250;
  581. var tasks = new List<Task>();
  582. var includedPersonTypes = new[] { PersonType.Actor, PersonType.Director };
  583. var people = RootFolder.RecursiveChildren
  584. .Where(c => c.People != null)
  585. .SelectMany(c => c.People.Where(p => includedPersonTypes.Contains(p.Type)))
  586. .DistinctBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
  587. .ToList();
  588. var numComplete = 0;
  589. foreach (var person in people)
  590. {
  591. if (tasks.Count > maxTasks)
  592. {
  593. await Task.WhenAll(tasks).ConfigureAwait(false);
  594. tasks.Clear();
  595. // Safe cancellation point, when there are no pending tasks
  596. cancellationToken.ThrowIfCancellationRequested();
  597. }
  598. // Avoid accessing the foreach variable within the closure
  599. var currentPerson = person;
  600. tasks.Add(Task.Run(async () =>
  601. {
  602. cancellationToken.ThrowIfCancellationRequested();
  603. try
  604. {
  605. await GetPerson(currentPerson.Name, cancellationToken, allowSlowProviders: true).ConfigureAwait(false);
  606. }
  607. catch (IOException ex)
  608. {
  609. _logger.ErrorException("Error validating IBN entry {0}", ex, currentPerson.Name);
  610. }
  611. // Update progress
  612. lock (progress)
  613. {
  614. numComplete++;
  615. double percent = numComplete;
  616. percent /= people.Count;
  617. progress.Report(100 * percent);
  618. }
  619. }));
  620. }
  621. await Task.WhenAll(tasks).ConfigureAwait(false);
  622. progress.Report(100);
  623. _logger.Info("People validation complete");
  624. }
  625. /// <summary>
  626. /// Reloads the root media folder
  627. /// </summary>
  628. /// <param name="progress">The progress.</param>
  629. /// <param name="cancellationToken">The cancellation token.</param>
  630. /// <returns>Task.</returns>
  631. public async Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  632. {
  633. _logger.Info("Validating media library");
  634. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  635. // Start by just validating the children of the root, but go no further
  636. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false);
  637. foreach (var folder in _userManager.Users.Select(u => u.RootFolder).Distinct())
  638. {
  639. await ValidateCollectionFolders(folder, cancellationToken).ConfigureAwait(false);
  640. }
  641. // Now validate the entire media library
  642. await RootFolder.ValidateChildren(progress, cancellationToken, recursive: true).ConfigureAwait(false);
  643. }
  644. /// <summary>
  645. /// Validates only the collection folders for a User and goes no further
  646. /// </summary>
  647. /// <param name="userRootFolder">The user root folder.</param>
  648. /// <param name="cancellationToken">The cancellation token.</param>
  649. /// <returns>Task.</returns>
  650. private async Task ValidateCollectionFolders(UserRootFolder userRootFolder, CancellationToken cancellationToken)
  651. {
  652. _logger.Info("Validating collection folders within {0}", userRootFolder.Path);
  653. await userRootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  654. cancellationToken.ThrowIfCancellationRequested();
  655. await userRootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false).ConfigureAwait(false);
  656. }
  657. /// <summary>
  658. /// Gets the default view.
  659. /// </summary>
  660. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  661. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  662. {
  663. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  664. }
  665. /// <summary>
  666. /// Gets the view.
  667. /// </summary>
  668. /// <param name="user">The user.</param>
  669. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  670. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  671. {
  672. return GetView(user.RootFolderPath);
  673. }
  674. /// <summary>
  675. /// Gets the view.
  676. /// </summary>
  677. /// <param name="path">The path.</param>
  678. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  679. private IEnumerable<VirtualFolderInfo> GetView(string path)
  680. {
  681. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  682. .Select(dir => new VirtualFolderInfo
  683. {
  684. Name = Path.GetFileName(dir),
  685. Locations = Directory.EnumerateFiles(dir, "*.lnk", SearchOption.TopDirectoryOnly).Select(FileSystem.ResolveShortcut).ToList()
  686. });
  687. }
  688. /// <summary>
  689. /// Gets the item by id.
  690. /// </summary>
  691. /// <param name="id">The id.</param>
  692. /// <returns>BaseItem.</returns>
  693. /// <exception cref="System.ArgumentNullException">id</exception>
  694. public BaseItem GetItemById(Guid id)
  695. {
  696. if (id == Guid.Empty)
  697. {
  698. throw new ArgumentNullException("id");
  699. }
  700. BaseItem item;
  701. LibraryItemsCache.TryGetValue(id, out item);
  702. return item;
  703. }
  704. /// <summary>
  705. /// Gets the intros.
  706. /// </summary>
  707. /// <param name="item">The item.</param>
  708. /// <param name="user">The user.</param>
  709. /// <returns>IEnumerable{System.String}.</returns>
  710. public IEnumerable<string> GetIntros(BaseItem item, User user)
  711. {
  712. return IntroProviders.SelectMany(i => i.GetIntros(item, user));
  713. }
  714. /// <summary>
  715. /// Sorts the specified sort by.
  716. /// </summary>
  717. /// <param name="items">The items.</param>
  718. /// <param name="user">The user.</param>
  719. /// <param name="sortBy">The sort by.</param>
  720. /// <param name="sortOrder">The sort order.</param>
  721. /// <returns>IEnumerable{BaseItem}.</returns>
  722. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  723. {
  724. var isFirst = true;
  725. IOrderedEnumerable<BaseItem> orderedItems = null;
  726. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  727. {
  728. if (isFirst)
  729. {
  730. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  731. }
  732. else
  733. {
  734. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  735. }
  736. isFirst = false;
  737. }
  738. return orderedItems ?? items;
  739. }
  740. /// <summary>
  741. /// Gets the comparer.
  742. /// </summary>
  743. /// <param name="name">The name.</param>
  744. /// <param name="user">The user.</param>
  745. /// <returns>IBaseItemComparer.</returns>
  746. private IBaseItemComparer GetComparer(string name, User user)
  747. {
  748. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  749. if (comparer != null)
  750. {
  751. // If it requires a user, create a new one, and assign the user
  752. if (comparer is IUserBaseItemComparer)
  753. {
  754. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  755. userComparer.User = user;
  756. userComparer.UserManager = _userManager;
  757. return userComparer;
  758. }
  759. }
  760. return comparer;
  761. }
  762. /// <summary>
  763. /// Saves the item.
  764. /// </summary>
  765. /// <param name="item">The item.</param>
  766. /// <param name="cancellationToken">The cancellation token.</param>
  767. /// <returns>Task.</returns>
  768. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  769. {
  770. return ItemRepository.SaveItem(item, cancellationToken);
  771. }
  772. /// <summary>
  773. /// Retrieves the item.
  774. /// </summary>
  775. /// <param name="id">The id.</param>
  776. /// <returns>Task{BaseItem}.</returns>
  777. public BaseItem RetrieveItem(Guid id)
  778. {
  779. return ItemRepository.RetrieveItem(id);
  780. }
  781. /// <summary>
  782. /// Saves the children.
  783. /// </summary>
  784. /// <param name="id">The id.</param>
  785. /// <param name="children">The children.</param>
  786. /// <param name="cancellationToken">The cancellation token.</param>
  787. /// <returns>Task.</returns>
  788. public Task SaveChildren(Guid id, IEnumerable<BaseItem> children, CancellationToken cancellationToken)
  789. {
  790. return ItemRepository.SaveChildren(id, children, cancellationToken);
  791. }
  792. /// <summary>
  793. /// Retrieves the children.
  794. /// </summary>
  795. /// <param name="parent">The parent.</param>
  796. /// <returns>IEnumerable{BaseItem}.</returns>
  797. public IEnumerable<BaseItem> RetrieveChildren(Folder parent)
  798. {
  799. return ItemRepository.RetrieveChildren(parent);
  800. }
  801. }
  802. }