LibraryManager.cs 34 KB

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