LibraryManager.cs 30 KB

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