LibraryManager.cs 25 KB

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