LibraryManager.cs 32 KB

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