LibraryManager.cs 36 KB

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