LibraryManager.cs 26 KB

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