LibraryManager.cs 29 KB

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