LibraryManager.cs 26 KB

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