LibraryManager.cs 27 KB

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