LibraryManager.cs 30 KB

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