2
0

LibraryManager.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  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. // Can't add these right now because there could be separate instances with the same id.
  235. //items.AddRange(_userManager.Users.Select(i => i.RootFolder).Distinct().ToList());
  236. items.AddRange(_userManager.Users.SelectMany(i => i.RootFolder.Children).Where(i => !(i is BasePluginFolder)).Distinct().ToList());
  237. return new ConcurrentDictionary<Guid,BaseItem>(items.ToDictionary(i => i.Id));
  238. }
  239. /// <summary>
  240. /// Updates the library cache.
  241. /// </summary>
  242. /// <param name="args">The <see cref="ChildrenChangedEventArgs"/> instance containing the event data.</param>
  243. private void UpdateLibraryCache(ChildrenChangedEventArgs args)
  244. {
  245. UpdateItemInLibraryCache(args.Folder);
  246. foreach (var item in args.ItemsAdded)
  247. {
  248. UpdateItemInLibraryCache(item);
  249. }
  250. foreach (var item in args.ItemsUpdated)
  251. {
  252. UpdateItemInLibraryCache(item);
  253. }
  254. }
  255. /// <summary>
  256. /// Updates the item in library cache.
  257. /// </summary>
  258. /// <param name="item">The item.</param>
  259. private void UpdateItemInLibraryCache(BaseItem item)
  260. {
  261. LibraryItemsCache.AddOrUpdate(item.Id, item, delegate { return item; });
  262. foreach (var trailer in item.LocalTrailers)
  263. {
  264. // Prevent access to foreach variable in closure
  265. var trailer1 = trailer;
  266. LibraryItemsCache.AddOrUpdate(trailer.Id, trailer, delegate { return trailer1; });
  267. }
  268. var movie = item as Movie;
  269. if (movie != null)
  270. {
  271. foreach (var special in movie.SpecialFeatures)
  272. {
  273. // Prevent access to foreach variable in closure
  274. Video special1 = special;
  275. LibraryItemsCache.AddOrUpdate(special.Id, special, delegate { return special1; });
  276. }
  277. }
  278. }
  279. /// <summary>
  280. /// Resolves the item.
  281. /// </summary>
  282. /// <param name="args">The args.</param>
  283. /// <returns>BaseItem.</returns>
  284. public BaseItem ResolveItem(ItemResolveArgs args)
  285. {
  286. var item = EntityResolvers.Select(r => r.ResolvePath(args)).FirstOrDefault(i => i != null);
  287. if (item != null)
  288. {
  289. ResolverHelper.SetInitialItemValues(item, args);
  290. // Now handle the issue with posibly having the same item referenced from multiple physical
  291. // places within the library. Be sure we always end up with just one instance.
  292. if (item is IByReferenceItem)
  293. {
  294. item = GetOrAddByReferenceItem(item);
  295. }
  296. }
  297. return item;
  298. }
  299. /// <summary>
  300. /// Ensure supplied item has only one instance throughout
  301. /// </summary>
  302. /// <param name="item"></param>
  303. /// <returns>The proper instance to the item</returns>
  304. public BaseItem GetOrAddByReferenceItem(BaseItem item)
  305. {
  306. // Add this item to our list if not there already
  307. if (!ByReferenceItems.TryAdd(item.Id, item))
  308. {
  309. // Already there - return the existing reference
  310. item = ByReferenceItems[item.Id];
  311. }
  312. return item;
  313. }
  314. /// <summary>
  315. /// Resolves a path into a BaseItem
  316. /// </summary>
  317. /// <param name="path">The path.</param>
  318. /// <param name="parent">The parent.</param>
  319. /// <param name="fileInfo">The file info.</param>
  320. /// <returns>BaseItem.</returns>
  321. /// <exception cref="System.ArgumentNullException"></exception>
  322. public BaseItem ResolvePath(string path, Folder parent = null, WIN32_FIND_DATA? fileInfo = null)
  323. {
  324. if (string.IsNullOrEmpty(path))
  325. {
  326. throw new ArgumentNullException();
  327. }
  328. fileInfo = fileInfo ?? FileSystem.GetFileData(path);
  329. if (!fileInfo.HasValue)
  330. {
  331. return null;
  332. }
  333. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths)
  334. {
  335. Parent = parent,
  336. Path = path,
  337. FileInfo = fileInfo.Value
  338. };
  339. // Return null if ignore rules deem that we should do so
  340. if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(args)))
  341. {
  342. return null;
  343. }
  344. // Gather child folder and files
  345. if (args.IsDirectory)
  346. {
  347. // When resolving the root, we need it's grandchildren (children of user views)
  348. var flattenFolderDepth = args.IsPhysicalRoot ? 2 : 0;
  349. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, _logger, flattenFolderDepth: flattenFolderDepth, args: args);
  350. }
  351. // Check to see if we should resolve based on our contents
  352. if (args.IsDirectory && !ShouldResolvePathContents(args))
  353. {
  354. return null;
  355. }
  356. return ResolveItem(args);
  357. }
  358. /// <summary>
  359. /// Determines whether a path should be ignored based on its contents - called after the contents have been read
  360. /// </summary>
  361. /// <param name="args">The args.</param>
  362. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  363. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  364. {
  365. // Ignore any folders containing a file called .ignore
  366. return !args.ContainsFileSystemEntryByName(".ignore");
  367. }
  368. /// <summary>
  369. /// Resolves a set of files into a list of BaseItem
  370. /// </summary>
  371. /// <typeparam name="T"></typeparam>
  372. /// <param name="files">The files.</param>
  373. /// <param name="parent">The parent.</param>
  374. /// <returns>List{``0}.</returns>
  375. public List<T> ResolvePaths<T>(IEnumerable<WIN32_FIND_DATA> files, Folder parent)
  376. where T : BaseItem
  377. {
  378. var list = new List<T>();
  379. Parallel.ForEach(files, f =>
  380. {
  381. try
  382. {
  383. var item = ResolvePath(f.Path, parent, f) as T;
  384. if (item != null)
  385. {
  386. lock (list)
  387. {
  388. list.Add(item);
  389. }
  390. }
  391. }
  392. catch (Exception ex)
  393. {
  394. _logger.ErrorException("Error resolving path {0}", ex, f.Path);
  395. }
  396. });
  397. return list;
  398. }
  399. /// <summary>
  400. /// Creates the root media folder
  401. /// </summary>
  402. /// <returns>AggregateFolder.</returns>
  403. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  404. public AggregateFolder CreateRootFolder()
  405. {
  406. var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
  407. var rootFolder = Kernel.ItemRepository.RetrieveItem(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(rootFolderPath);
  408. // Add in the plug-in folders
  409. foreach (var child in PluginFolderCreators)
  410. {
  411. rootFolder.AddVirtualChild(child.GetFolder());
  412. }
  413. return rootFolder;
  414. }
  415. /// <summary>
  416. /// Gets a Person
  417. /// </summary>
  418. /// <param name="name">The name.</param>
  419. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  420. /// <returns>Task{Person}.</returns>
  421. public Task<Person> GetPerson(string name, bool allowSlowProviders = false)
  422. {
  423. return GetPerson(name, CancellationToken.None, allowSlowProviders);
  424. }
  425. /// <summary>
  426. /// Gets a Person
  427. /// </summary>
  428. /// <param name="name">The name.</param>
  429. /// <param name="cancellationToken">The cancellation token.</param>
  430. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  431. /// <returns>Task{Person}.</returns>
  432. private Task<Person> GetPerson(string name, CancellationToken cancellationToken, bool allowSlowProviders = false)
  433. {
  434. return GetImagesByNameItem<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name, cancellationToken, allowSlowProviders);
  435. }
  436. /// <summary>
  437. /// Gets a Studio
  438. /// </summary>
  439. /// <param name="name">The name.</param>
  440. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  441. /// <returns>Task{Studio}.</returns>
  442. public Task<Studio> GetStudio(string name, bool allowSlowProviders = false)
  443. {
  444. return GetImagesByNameItem<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name, CancellationToken.None, allowSlowProviders);
  445. }
  446. /// <summary>
  447. /// Gets a Genre
  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{Genre}.</returns>
  452. public Task<Genre> GetGenre(string name, bool allowSlowProviders = false)
  453. {
  454. return GetImagesByNameItem<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name, CancellationToken.None, allowSlowProviders);
  455. }
  456. /// <summary>
  457. /// The us culture
  458. /// </summary>
  459. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  460. /// <summary>
  461. /// Gets a Year
  462. /// </summary>
  463. /// <param name="value">The value.</param>
  464. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  465. /// <returns>Task{Year}.</returns>
  466. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  467. public Task<Year> GetYear(int value, bool allowSlowProviders = false)
  468. {
  469. if (value <= 0)
  470. {
  471. throw new ArgumentOutOfRangeException();
  472. }
  473. return GetImagesByNameItem<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture), CancellationToken.None, allowSlowProviders);
  474. }
  475. /// <summary>
  476. /// The images by name item cache
  477. /// </summary>
  478. private readonly ConcurrentDictionary<string, object> ImagesByNameItemCache = new ConcurrentDictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  479. /// <summary>
  480. /// Generically retrieves an IBN item
  481. /// </summary>
  482. /// <typeparam name="T"></typeparam>
  483. /// <param name="path">The path.</param>
  484. /// <param name="name">The name.</param>
  485. /// <param name="cancellationToken">The cancellation token.</param>
  486. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  487. /// <returns>Task{``0}.</returns>
  488. /// <exception cref="System.ArgumentNullException"></exception>
  489. private Task<T> GetImagesByNameItem<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  490. where T : BaseItem, new()
  491. {
  492. if (string.IsNullOrEmpty(path))
  493. {
  494. throw new ArgumentNullException();
  495. }
  496. if (string.IsNullOrEmpty(name))
  497. {
  498. throw new ArgumentNullException();
  499. }
  500. var key = Path.Combine(path, FileSystem.GetValidFilename(name));
  501. var obj = ImagesByNameItemCache.GetOrAdd(key, keyname => CreateImagesByNameItem<T>(path, name, cancellationToken, allowSlowProviders));
  502. return obj as Task<T>;
  503. }
  504. /// <summary>
  505. /// Creates an IBN item based on a given path
  506. /// </summary>
  507. /// <typeparam name="T"></typeparam>
  508. /// <param name="path">The path.</param>
  509. /// <param name="name">The name.</param>
  510. /// <param name="cancellationToken">The cancellation token.</param>
  511. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  512. /// <returns>Task{``0}.</returns>
  513. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  514. private async Task<T> CreateImagesByNameItem<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  515. where T : BaseItem, new()
  516. {
  517. cancellationToken.ThrowIfCancellationRequested();
  518. _logger.Debug("Creating {0}: {1}", typeof(T).Name, name);
  519. path = Path.Combine(path, FileSystem.GetValidFilename(name));
  520. var fileInfo = FileSystem.GetFileData(path);
  521. var isNew = false;
  522. if (!fileInfo.HasValue)
  523. {
  524. Directory.CreateDirectory(path);
  525. fileInfo = FileSystem.GetFileData(path);
  526. if (!fileInfo.HasValue)
  527. {
  528. throw new IOException("Path not created: " + path);
  529. }
  530. isNew = true;
  531. }
  532. cancellationToken.ThrowIfCancellationRequested();
  533. var id = path.GetMBId(typeof(T));
  534. var item = Kernel.ItemRepository.RetrieveItem(id) as T;
  535. if (item == null)
  536. {
  537. item = new T
  538. {
  539. Name = name,
  540. Id = id,
  541. DateCreated = fileInfo.Value.CreationTimeUtc,
  542. DateModified = fileInfo.Value.LastWriteTimeUtc,
  543. Path = path
  544. };
  545. isNew = true;
  546. }
  547. cancellationToken.ThrowIfCancellationRequested();
  548. // Set this now so we don't cause additional file system access during provider executions
  549. item.ResetResolveArgs(fileInfo);
  550. await item.RefreshMetadata(cancellationToken, isNew, allowSlowProviders: allowSlowProviders).ConfigureAwait(false);
  551. cancellationToken.ThrowIfCancellationRequested();
  552. return item;
  553. }
  554. /// <summary>
  555. /// Validate and refresh the People sub-set of the IBN.
  556. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  557. /// </summary>
  558. /// <param name="cancellationToken">The cancellation token.</param>
  559. /// <param name="progress">The progress.</param>
  560. /// <returns>Task.</returns>
  561. public async Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  562. {
  563. // Clear the IBN cache
  564. ImagesByNameItemCache.Clear();
  565. const int maxTasks = 250;
  566. var tasks = new List<Task>();
  567. var includedPersonTypes = new[] { PersonType.Actor, PersonType.Director };
  568. var people = RootFolder.RecursiveChildren
  569. .Where(c => c.People != null)
  570. .SelectMany(c => c.People.Where(p => includedPersonTypes.Contains(p.Type)))
  571. .DistinctBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
  572. .ToList();
  573. var numComplete = 0;
  574. foreach (var person in people)
  575. {
  576. if (tasks.Count > maxTasks)
  577. {
  578. await Task.WhenAll(tasks).ConfigureAwait(false);
  579. tasks.Clear();
  580. // Safe cancellation point, when there are no pending tasks
  581. cancellationToken.ThrowIfCancellationRequested();
  582. }
  583. // Avoid accessing the foreach variable within the closure
  584. var currentPerson = person;
  585. tasks.Add(Task.Run(async () =>
  586. {
  587. cancellationToken.ThrowIfCancellationRequested();
  588. try
  589. {
  590. await GetPerson(currentPerson.Name, cancellationToken, allowSlowProviders: true).ConfigureAwait(false);
  591. }
  592. catch (IOException ex)
  593. {
  594. _logger.ErrorException("Error validating IBN entry {0}", ex, currentPerson.Name);
  595. }
  596. // Update progress
  597. lock (progress)
  598. {
  599. numComplete++;
  600. double percent = numComplete;
  601. percent /= people.Count;
  602. progress.Report(100 * percent);
  603. }
  604. }));
  605. }
  606. await Task.WhenAll(tasks).ConfigureAwait(false);
  607. progress.Report(100);
  608. _logger.Info("People validation complete");
  609. }
  610. /// <summary>
  611. /// Reloads the root media folder
  612. /// </summary>
  613. /// <param name="progress">The progress.</param>
  614. /// <param name="cancellationToken">The cancellation token.</param>
  615. /// <returns>Task.</returns>
  616. public async Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  617. {
  618. _logger.Info("Validating media library");
  619. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  620. // Start by just validating the children of the root, but go no further
  621. await RootFolder.ValidateChildren(new Progress<double> { }, cancellationToken, recursive: false);
  622. // Validate only the collection folders for each user, just to make them available as quickly as possible
  623. var userCollectionFolderTasks = _userManager.Users.AsParallel().Select(user => user.ValidateCollectionFolders(new Progress<double> { }, cancellationToken));
  624. await Task.WhenAll(userCollectionFolderTasks).ConfigureAwait(false);
  625. // Now validate the entire media library
  626. await RootFolder.ValidateChildren(progress, cancellationToken, recursive: true).ConfigureAwait(false);
  627. }
  628. /// <summary>
  629. /// Saves display preferences for a Folder
  630. /// </summary>
  631. /// <param name="user">The user.</param>
  632. /// <param name="folder">The folder.</param>
  633. /// <param name="data">The data.</param>
  634. /// <returns>Task.</returns>
  635. public Task SaveDisplayPreferencesForFolder(User user, Folder folder, DisplayPreferences data)
  636. {
  637. // Need to update all items with the same DisplayPreferencesId
  638. foreach (var child in RootFolder.GetRecursiveChildren(user)
  639. .OfType<Folder>()
  640. .Where(i => i.DisplayPreferencesId == folder.DisplayPreferencesId))
  641. {
  642. child.AddOrUpdateDisplayPreferences(user, data);
  643. }
  644. return Kernel.DisplayPreferencesRepository.SaveDisplayPreferences(folder, CancellationToken.None);
  645. }
  646. /// <summary>
  647. /// Gets the default view.
  648. /// </summary>
  649. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  650. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  651. {
  652. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  653. }
  654. /// <summary>
  655. /// Gets the view.
  656. /// </summary>
  657. /// <param name="user">The user.</param>
  658. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  659. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  660. {
  661. return GetView(user.RootFolderPath);
  662. }
  663. /// <summary>
  664. /// Gets the view.
  665. /// </summary>
  666. /// <param name="path">The path.</param>
  667. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  668. private IEnumerable<VirtualFolderInfo> GetView(string path)
  669. {
  670. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  671. .Select(dir => new VirtualFolderInfo
  672. {
  673. Name = Path.GetFileName(dir),
  674. Locations = Directory.EnumerateFiles(dir, "*.lnk", SearchOption.TopDirectoryOnly).Select(FileSystem.ResolveShortcut).ToList()
  675. });
  676. }
  677. /// <summary>
  678. /// Gets the item by id.
  679. /// </summary>
  680. /// <param name="id">The id.</param>
  681. /// <returns>BaseItem.</returns>
  682. /// <exception cref="System.ArgumentNullException">id</exception>
  683. public BaseItem GetItemById(Guid id)
  684. {
  685. if (id == Guid.Empty)
  686. {
  687. throw new ArgumentNullException("id");
  688. }
  689. BaseItem item;
  690. LibraryItemsCache.TryGetValue(id, out item);
  691. return item;
  692. }
  693. /// <summary>
  694. /// Gets the intros.
  695. /// </summary>
  696. /// <param name="item">The item.</param>
  697. /// <param name="user">The user.</param>
  698. /// <returns>IEnumerable{System.String}.</returns>
  699. public IEnumerable<string> GetIntros(BaseItem item, User user)
  700. {
  701. return IntroProviders.SelectMany(i => i.GetIntros(item, user));
  702. }
  703. /// <summary>
  704. /// Sorts the specified sort by.
  705. /// </summary>
  706. /// <param name="items">The items.</param>
  707. /// <param name="user">The user.</param>
  708. /// <param name="sortBy">The sort by.</param>
  709. /// <param name="sortOrder">The sort order.</param>
  710. /// <returns>IEnumerable{BaseItem}.</returns>
  711. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  712. {
  713. var isFirst = true;
  714. IOrderedEnumerable<BaseItem> orderedItems = null;
  715. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  716. {
  717. if (isFirst)
  718. {
  719. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  720. }
  721. else
  722. {
  723. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  724. }
  725. isFirst = false;
  726. }
  727. return orderedItems ?? items;
  728. }
  729. /// <summary>
  730. /// Gets the comparer.
  731. /// </summary>
  732. /// <param name="name">The name.</param>
  733. /// <param name="user">The user.</param>
  734. /// <returns>IBaseItemComparer.</returns>
  735. private IBaseItemComparer GetComparer(string name, User user)
  736. {
  737. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  738. if (comparer != null)
  739. {
  740. // If it requires a user, create a new one, and assign the user
  741. if (comparer is IUserBaseItemComparer)
  742. {
  743. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  744. userComparer.User = user;
  745. return userComparer;
  746. }
  747. }
  748. return comparer;
  749. }
  750. }
  751. }