LibraryManager.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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.ScheduledTasks;
  10. using MediaBrowser.Model.Entities;
  11. using MediaBrowser.Model.Logging;
  12. using MediaBrowser.Server.Implementations.Library.Resolvers;
  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<IResolverIgnoreRule> 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<IItemResolver> 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<IResolverIgnoreRule> rules, IEnumerable<IVirtualFolderCreator> pluginFolders, IEnumerable<IItemResolver> 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. var item = EntityResolvers.Select(r => r.ResolvePath(args)).FirstOrDefault(i => i != null);
  173. if (item != null)
  174. {
  175. ResolverHelper.SetInitialItemValues(item, args);
  176. }
  177. return item;
  178. }
  179. /// <summary>
  180. /// Resolves a path into a BaseItem
  181. /// </summary>
  182. /// <param name="path">The path.</param>
  183. /// <param name="parent">The parent.</param>
  184. /// <param name="fileInfo">The file info.</param>
  185. /// <returns>BaseItem.</returns>
  186. /// <exception cref="System.ArgumentNullException"></exception>
  187. public BaseItem ResolvePath(string path, Folder parent = null, WIN32_FIND_DATA? fileInfo = null)
  188. {
  189. if (string.IsNullOrEmpty(path))
  190. {
  191. throw new ArgumentNullException();
  192. }
  193. fileInfo = fileInfo ?? FileSystem.GetFileData(path);
  194. if (!fileInfo.HasValue)
  195. {
  196. return null;
  197. }
  198. var args = new ItemResolveArgs
  199. {
  200. Parent = parent,
  201. Path = path,
  202. FileInfo = fileInfo.Value
  203. };
  204. // Return null if ignore rules deem that we should do so
  205. if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(args)))
  206. {
  207. return null;
  208. }
  209. // Gather child folder and files
  210. if (args.IsDirectory)
  211. {
  212. // When resolving the root, we need it's grandchildren (children of user views)
  213. var flattenFolderDepth = args.IsPhysicalRoot ? 2 : 0;
  214. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, _logger, flattenFolderDepth: flattenFolderDepth, args: args);
  215. }
  216. // Check to see if we should resolve based on our contents
  217. if (args.IsDirectory && !ShouldResolvePathContents(args))
  218. {
  219. return null;
  220. }
  221. return ResolveItem(args);
  222. }
  223. /// <summary>
  224. /// Determines whether a path should be ignored based on its contents - called after the contents have been read
  225. /// </summary>
  226. /// <param name="args">The args.</param>
  227. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  228. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  229. {
  230. // Ignore any folders containing a file called .ignore
  231. return !args.ContainsFileSystemEntryByName(".ignore");
  232. }
  233. /// <summary>
  234. /// Resolves a set of files into a list of BaseItem
  235. /// </summary>
  236. /// <typeparam name="T"></typeparam>
  237. /// <param name="files">The files.</param>
  238. /// <param name="parent">The parent.</param>
  239. /// <returns>List{``0}.</returns>
  240. public List<T> ResolvePaths<T>(IEnumerable<WIN32_FIND_DATA> files, Folder parent)
  241. where T : BaseItem
  242. {
  243. var list = new List<T>();
  244. Parallel.ForEach(files, f =>
  245. {
  246. try
  247. {
  248. var item = ResolvePath(f.Path, parent, f) as T;
  249. if (item != null)
  250. {
  251. lock (list)
  252. {
  253. list.Add(item);
  254. }
  255. }
  256. }
  257. catch (Exception ex)
  258. {
  259. _logger.ErrorException("Error resolving path {0}", ex, f.Path);
  260. }
  261. });
  262. return list;
  263. }
  264. /// <summary>
  265. /// Creates the root media folder
  266. /// </summary>
  267. /// <returns>AggregateFolder.</returns>
  268. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  269. public AggregateFolder CreateRootFolder()
  270. {
  271. var rootFolderPath = Kernel.ApplicationPaths.RootFolderPath;
  272. var rootFolder = Kernel.ItemRepository.RetrieveItem(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(rootFolderPath);
  273. // Add in the plug-in folders
  274. foreach (var child in PluginFolderCreators)
  275. {
  276. rootFolder.AddVirtualChild(child.GetFolder());
  277. }
  278. return rootFolder;
  279. }
  280. /// <summary>
  281. /// Gets a Person
  282. /// </summary>
  283. /// <param name="name">The name.</param>
  284. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  285. /// <returns>Task{Person}.</returns>
  286. public Task<Person> GetPerson(string name, bool allowSlowProviders = false)
  287. {
  288. return GetPerson(name, CancellationToken.None, allowSlowProviders);
  289. }
  290. /// <summary>
  291. /// Gets a Person
  292. /// </summary>
  293. /// <param name="name">The name.</param>
  294. /// <param name="cancellationToken">The cancellation token.</param>
  295. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  296. /// <returns>Task{Person}.</returns>
  297. private Task<Person> GetPerson(string name, CancellationToken cancellationToken, bool allowSlowProviders = false)
  298. {
  299. return GetImagesByNameItem<Person>(Kernel.ApplicationPaths.PeoplePath, name, cancellationToken, allowSlowProviders);
  300. }
  301. /// <summary>
  302. /// Gets a Studio
  303. /// </summary>
  304. /// <param name="name">The name.</param>
  305. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  306. /// <returns>Task{Studio}.</returns>
  307. public Task<Studio> GetStudio(string name, bool allowSlowProviders = false)
  308. {
  309. return GetImagesByNameItem<Studio>(Kernel.ApplicationPaths.StudioPath, name, CancellationToken.None, allowSlowProviders);
  310. }
  311. /// <summary>
  312. /// Gets a Genre
  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{Genre}.</returns>
  317. public Task<Genre> GetGenre(string name, bool allowSlowProviders = false)
  318. {
  319. return GetImagesByNameItem<Genre>(Kernel.ApplicationPaths.GenrePath, name, CancellationToken.None, allowSlowProviders);
  320. }
  321. /// <summary>
  322. /// The us culture
  323. /// </summary>
  324. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  325. /// <summary>
  326. /// Gets a Year
  327. /// </summary>
  328. /// <param name="value">The value.</param>
  329. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  330. /// <returns>Task{Year}.</returns>
  331. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  332. public Task<Year> GetYear(int value, bool allowSlowProviders = false)
  333. {
  334. if (value <= 0)
  335. {
  336. throw new ArgumentOutOfRangeException();
  337. }
  338. return GetImagesByNameItem<Year>(Kernel.ApplicationPaths.YearPath, value.ToString(UsCulture), CancellationToken.None, allowSlowProviders);
  339. }
  340. /// <summary>
  341. /// The images by name item cache
  342. /// </summary>
  343. private readonly ConcurrentDictionary<string, object> ImagesByNameItemCache = new ConcurrentDictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  344. /// <summary>
  345. /// Generically retrieves an IBN item
  346. /// </summary>
  347. /// <typeparam name="T"></typeparam>
  348. /// <param name="path">The path.</param>
  349. /// <param name="name">The name.</param>
  350. /// <param name="cancellationToken">The cancellation token.</param>
  351. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  352. /// <returns>Task{``0}.</returns>
  353. /// <exception cref="System.ArgumentNullException"></exception>
  354. private Task<T> GetImagesByNameItem<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  355. where T : BaseItem, new()
  356. {
  357. if (string.IsNullOrEmpty(path))
  358. {
  359. throw new ArgumentNullException();
  360. }
  361. if (string.IsNullOrEmpty(name))
  362. {
  363. throw new ArgumentNullException();
  364. }
  365. var key = Path.Combine(path, FileSystem.GetValidFilename(name));
  366. var obj = ImagesByNameItemCache.GetOrAdd(key, keyname => CreateImagesByNameItem<T>(path, name, cancellationToken, allowSlowProviders));
  367. return obj as Task<T>;
  368. }
  369. /// <summary>
  370. /// Creates an IBN item based on a given path
  371. /// </summary>
  372. /// <typeparam name="T"></typeparam>
  373. /// <param name="path">The path.</param>
  374. /// <param name="name">The name.</param>
  375. /// <param name="cancellationToken">The cancellation token.</param>
  376. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  377. /// <returns>Task{``0}.</returns>
  378. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  379. private async Task<T> CreateImagesByNameItem<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  380. where T : BaseItem, new()
  381. {
  382. cancellationToken.ThrowIfCancellationRequested();
  383. _logger.Debug("Creating {0}: {1}", typeof(T).Name, name);
  384. path = Path.Combine(path, FileSystem.GetValidFilename(name));
  385. var fileInfo = FileSystem.GetFileData(path);
  386. var isNew = false;
  387. if (!fileInfo.HasValue)
  388. {
  389. Directory.CreateDirectory(path);
  390. fileInfo = FileSystem.GetFileData(path);
  391. if (!fileInfo.HasValue)
  392. {
  393. throw new IOException("Path not created: " + path);
  394. }
  395. isNew = true;
  396. }
  397. cancellationToken.ThrowIfCancellationRequested();
  398. var id = path.GetMBId(typeof(T));
  399. var item = Kernel.ItemRepository.RetrieveItem(id) as T;
  400. if (item == null)
  401. {
  402. item = new T
  403. {
  404. Name = name,
  405. Id = id,
  406. DateCreated = fileInfo.Value.CreationTimeUtc,
  407. DateModified = fileInfo.Value.LastWriteTimeUtc,
  408. Path = path
  409. };
  410. isNew = true;
  411. }
  412. cancellationToken.ThrowIfCancellationRequested();
  413. // Set this now so we don't cause additional file system access during provider executions
  414. item.ResetResolveArgs(fileInfo);
  415. await item.RefreshMetadata(cancellationToken, isNew, allowSlowProviders: allowSlowProviders).ConfigureAwait(false);
  416. cancellationToken.ThrowIfCancellationRequested();
  417. return item;
  418. }
  419. /// <summary>
  420. /// Validate and refresh the People sub-set of the IBN.
  421. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  422. /// </summary>
  423. /// <param name="cancellationToken">The cancellation token.</param>
  424. /// <param name="progress">The progress.</param>
  425. /// <returns>Task.</returns>
  426. public async Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  427. {
  428. // Clear the IBN cache
  429. ImagesByNameItemCache.Clear();
  430. const int maxTasks = 250;
  431. var tasks = new List<Task>();
  432. var includedPersonTypes = new[] { PersonType.Actor, PersonType.Director };
  433. var people = RootFolder.RecursiveChildren
  434. .Where(c => c.People != null)
  435. .SelectMany(c => c.People.Where(p => includedPersonTypes.Contains(p.Type)))
  436. .DistinctBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
  437. .ToList();
  438. var numComplete = 0;
  439. foreach (var person in people)
  440. {
  441. if (tasks.Count > maxTasks)
  442. {
  443. await Task.WhenAll(tasks).ConfigureAwait(false);
  444. tasks.Clear();
  445. // Safe cancellation point, when there are no pending tasks
  446. cancellationToken.ThrowIfCancellationRequested();
  447. }
  448. // Avoid accessing the foreach variable within the closure
  449. var currentPerson = person;
  450. tasks.Add(Task.Run(async () =>
  451. {
  452. cancellationToken.ThrowIfCancellationRequested();
  453. try
  454. {
  455. await GetPerson(currentPerson.Name, cancellationToken, allowSlowProviders: true).ConfigureAwait(false);
  456. }
  457. catch (IOException ex)
  458. {
  459. _logger.ErrorException("Error validating IBN entry {0}", ex, currentPerson.Name);
  460. }
  461. // Update progress
  462. lock (progress)
  463. {
  464. numComplete++;
  465. double percent = numComplete;
  466. percent /= people.Count;
  467. progress.Report(100 * percent);
  468. }
  469. }));
  470. }
  471. await Task.WhenAll(tasks).ConfigureAwait(false);
  472. progress.Report(100);
  473. _logger.Info("People validation complete");
  474. }
  475. /// <summary>
  476. /// Reloads the root media folder
  477. /// </summary>
  478. /// <param name="progress">The progress.</param>
  479. /// <param name="cancellationToken">The cancellation token.</param>
  480. /// <returns>Task.</returns>
  481. public async Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  482. {
  483. _logger.Info("Validating media library");
  484. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  485. // Start by just validating the children of the root, but go no further
  486. await RootFolder.ValidateChildren(new Progress<double> { }, cancellationToken, recursive: false);
  487. // Validate only the collection folders for each user, just to make them available as quickly as possible
  488. var userCollectionFolderTasks = _userManager.Users.AsParallel().Select(user => user.ValidateCollectionFolders(new Progress<double> { }, cancellationToken));
  489. await Task.WhenAll(userCollectionFolderTasks).ConfigureAwait(false);
  490. // Now validate the entire media library
  491. await RootFolder.ValidateChildren(progress, cancellationToken, recursive: true).ConfigureAwait(false);
  492. foreach (var user in _userManager.Users)
  493. {
  494. await user.ValidateMediaLibrary(new Progress<double> { }, cancellationToken).ConfigureAwait(false);
  495. }
  496. }
  497. /// <summary>
  498. /// Saves display preferences for a Folder
  499. /// </summary>
  500. /// <param name="user">The user.</param>
  501. /// <param name="folder">The folder.</param>
  502. /// <param name="data">The data.</param>
  503. /// <returns>Task.</returns>
  504. public Task SaveDisplayPreferencesForFolder(User user, Folder folder, DisplayPreferences data)
  505. {
  506. // Need to update all items with the same DisplayPrefsId
  507. foreach (var child in RootFolder.GetRecursiveChildren(user)
  508. .OfType<Folder>()
  509. .Where(i => i.DisplayPrefsId == folder.DisplayPrefsId))
  510. {
  511. child.AddOrUpdateDisplayPrefs(user, data);
  512. }
  513. return Kernel.DisplayPreferencesRepository.SaveDisplayPrefs(folder, CancellationToken.None);
  514. }
  515. /// <summary>
  516. /// Gets the default view.
  517. /// </summary>
  518. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  519. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  520. {
  521. return GetView(Kernel.ApplicationPaths.DefaultUserViewsPath);
  522. }
  523. /// <summary>
  524. /// Gets the view.
  525. /// </summary>
  526. /// <param name="user">The user.</param>
  527. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  528. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  529. {
  530. return GetView(user.RootFolderPath);
  531. }
  532. /// <summary>
  533. /// Gets the view.
  534. /// </summary>
  535. /// <param name="path">The path.</param>
  536. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  537. private IEnumerable<VirtualFolderInfo> GetView(string path)
  538. {
  539. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  540. .Select(dir => new VirtualFolderInfo
  541. {
  542. Name = Path.GetFileName(dir),
  543. Locations = Directory.EnumerateFiles(dir, "*.lnk", SearchOption.TopDirectoryOnly).Select(FileSystem.ResolveShortcut).ToList()
  544. });
  545. }
  546. /// <summary>
  547. /// Finds a library item by Id and UserId.
  548. /// </summary>
  549. /// <param name="id">The id.</param>
  550. /// <param name="userId">The user id.</param>
  551. /// <param name="userManager">The user manager.</param>
  552. /// <returns>BaseItem.</returns>
  553. /// <exception cref="System.ArgumentNullException">id</exception>
  554. public BaseItem GetItemById(Guid id, Guid userId)
  555. {
  556. if (id == Guid.Empty)
  557. {
  558. throw new ArgumentNullException("id");
  559. }
  560. if (userId == Guid.Empty)
  561. {
  562. throw new ArgumentNullException("userId");
  563. }
  564. var user = _userManager.GetUserById(userId);
  565. var userRoot = user.RootFolder;
  566. return userRoot.FindItemById(id, user);
  567. }
  568. /// <summary>
  569. /// Gets the item by id.
  570. /// </summary>
  571. /// <param name="id">The id.</param>
  572. /// <returns>BaseItem.</returns>
  573. /// <exception cref="System.ArgumentNullException">id</exception>
  574. public BaseItem GetItemById(Guid id)
  575. {
  576. if (id == Guid.Empty)
  577. {
  578. throw new ArgumentNullException("id");
  579. }
  580. return RootFolder.FindItemById(id, null);
  581. }
  582. /// <summary>
  583. /// Gets the intros.
  584. /// </summary>
  585. /// <param name="item">The item.</param>
  586. /// <param name="user">The user.</param>
  587. /// <returns>IEnumerable{System.String}.</returns>
  588. public IEnumerable<string> GetIntros(BaseItem item, User user)
  589. {
  590. return IntroProviders.SelectMany(i => i.GetIntros(item, user));
  591. }
  592. }
  593. }