LibraryManager.cs 32 KB

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