LibraryManager.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.Progress;
  4. using MediaBrowser.Common.ScheduledTasks;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Entities.Audio;
  8. using MediaBrowser.Controller.Entities.Movies;
  9. using MediaBrowser.Controller.IO;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.Persistence;
  12. using MediaBrowser.Controller.Resolvers;
  13. using MediaBrowser.Controller.Sorting;
  14. using MediaBrowser.Model.Configuration;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.Logging;
  17. using MediaBrowser.Server.Implementations.ScheduledTasks;
  18. using MoreLinq;
  19. using System;
  20. using System.Collections.Concurrent;
  21. using System.Collections.Generic;
  22. using System.Globalization;
  23. using System.IO;
  24. using System.Linq;
  25. using System.Threading;
  26. using System.Threading.Tasks;
  27. using SortOrder = MediaBrowser.Model.Entities.SortOrder;
  28. namespace MediaBrowser.Server.Implementations.Library
  29. {
  30. /// <summary>
  31. /// Class LibraryManager
  32. /// </summary>
  33. public class LibraryManager : ILibraryManager
  34. {
  35. /// <summary>
  36. /// Gets the intro providers.
  37. /// </summary>
  38. /// <value>The intro providers.</value>
  39. private IEnumerable<IIntroProvider> IntroProviders { get; set; }
  40. /// <summary>
  41. /// Gets the list of entity resolution ignore rules
  42. /// </summary>
  43. /// <value>The entity resolution ignore rules.</value>
  44. private IEnumerable<IResolverIgnoreRule> EntityResolutionIgnoreRules { get; set; }
  45. /// <summary>
  46. /// Gets the list of BasePluginFolders added by plugins
  47. /// </summary>
  48. /// <value>The plugin folders.</value>
  49. private IEnumerable<IVirtualFolderCreator> PluginFolderCreators { get; set; }
  50. /// <summary>
  51. /// Gets the list of currently registered entity resolvers
  52. /// </summary>
  53. /// <value>The entity resolvers enumerable.</value>
  54. private IEnumerable<IItemResolver> EntityResolvers { get; set; }
  55. /// <summary>
  56. /// Gets or sets the comparers.
  57. /// </summary>
  58. /// <value>The comparers.</value>
  59. private IEnumerable<IBaseItemComparer> Comparers { get; set; }
  60. /// <summary>
  61. /// Gets the active item repository
  62. /// </summary>
  63. /// <value>The item repository.</value>
  64. public IItemRepository ItemRepository { get; set; }
  65. #region LibraryChanged Event
  66. /// <summary>
  67. /// Fires whenever any validation routine adds or removes items. The added and removed items are properties of the args.
  68. /// *** Will fire asynchronously. ***
  69. /// </summary>
  70. public event EventHandler<ChildrenChangedEventArgs> LibraryChanged;
  71. /// <summary>
  72. /// Reports the library changed.
  73. /// </summary>
  74. /// <param name="args">The <see cref="ChildrenChangedEventArgs" /> instance containing the event data.</param>
  75. public void ReportLibraryChanged(ChildrenChangedEventArgs args)
  76. {
  77. UpdateLibraryCache(args);
  78. EventHelper.FireEventIfNotNull(LibraryChanged, this, args, _logger);
  79. }
  80. #endregion
  81. /// <summary>
  82. /// The _logger
  83. /// </summary>
  84. private readonly ILogger _logger;
  85. /// <summary>
  86. /// The _task manager
  87. /// </summary>
  88. private readonly ITaskManager _taskManager;
  89. /// <summary>
  90. /// The _user manager
  91. /// </summary>
  92. private readonly IUserManager _userManager;
  93. private readonly IUserDataRepository _userDataRepository;
  94. /// <summary>
  95. /// Gets or sets the configuration manager.
  96. /// </summary>
  97. /// <value>The configuration manager.</value>
  98. private IServerConfigurationManager ConfigurationManager { get; set; }
  99. /// <summary>
  100. /// A collection of items that may be referenced from multiple physical places in the library
  101. /// (typically, multiple user roots). We store them here and be sure they all reference a
  102. /// single instance.
  103. /// </summary>
  104. private ConcurrentDictionary<Guid, BaseItem> ByReferenceItems { get; set; }
  105. private ConcurrentDictionary<Guid, BaseItem> _libraryItemsCache;
  106. private object _libraryItemsCacheSyncLock = new object();
  107. private bool _libraryItemsCacheInitialized;
  108. private ConcurrentDictionary<Guid, BaseItem> LibraryItemsCache
  109. {
  110. get
  111. {
  112. LazyInitializer.EnsureInitialized(ref _libraryItemsCache, ref _libraryItemsCacheInitialized, ref _libraryItemsCacheSyncLock, CreateLibraryItemsCache);
  113. return _libraryItemsCache;
  114. }
  115. }
  116. private readonly ConcurrentDictionary<string, UserRootFolder> _userRootFolders =
  117. new ConcurrentDictionary<string, UserRootFolder>();
  118. /// <summary>
  119. /// Initializes a new instance of the <see cref="LibraryManager" /> class.
  120. /// </summary>
  121. /// <param name="logger">The logger.</param>
  122. /// <param name="taskManager">The task manager.</param>
  123. /// <param name="userManager">The user manager.</param>
  124. /// <param name="configurationManager">The configuration manager.</param>
  125. /// <param name="userDataRepository">The user data repository.</param>
  126. public LibraryManager(ILogger logger, ITaskManager taskManager, IUserManager userManager, IServerConfigurationManager configurationManager, IUserDataRepository userDataRepository)
  127. {
  128. _logger = logger;
  129. _taskManager = taskManager;
  130. _userManager = userManager;
  131. ConfigurationManager = configurationManager;
  132. _userDataRepository = userDataRepository;
  133. ByReferenceItems = new ConcurrentDictionary<Guid, BaseItem>();
  134. ConfigurationManager.ConfigurationUpdated += ConfigurationUpdated;
  135. RecordConfigurationValues(configurationManager.Configuration);
  136. }
  137. /// <summary>
  138. /// Adds the parts.
  139. /// </summary>
  140. /// <param name="rules">The rules.</param>
  141. /// <param name="pluginFolders">The plugin folders.</param>
  142. /// <param name="resolvers">The resolvers.</param>
  143. /// <param name="introProviders">The intro providers.</param>
  144. /// <param name="itemComparers">The item comparers.</param>
  145. public void AddParts(IEnumerable<IResolverIgnoreRule> rules,
  146. IEnumerable<IVirtualFolderCreator> pluginFolders,
  147. IEnumerable<IItemResolver> resolvers,
  148. IEnumerable<IIntroProvider> introProviders,
  149. IEnumerable<IBaseItemComparer> itemComparers)
  150. {
  151. EntityResolutionIgnoreRules = rules;
  152. PluginFolderCreators = pluginFolders;
  153. EntityResolvers = resolvers.OrderBy(i => i.Priority).ToArray();
  154. IntroProviders = introProviders;
  155. Comparers = itemComparers;
  156. }
  157. /// <summary>
  158. /// The _root folder
  159. /// </summary>
  160. private AggregateFolder _rootFolder;
  161. /// <summary>
  162. /// The _root folder sync lock
  163. /// </summary>
  164. private object _rootFolderSyncLock = new object();
  165. /// <summary>
  166. /// The _root folder initialized
  167. /// </summary>
  168. private bool _rootFolderInitialized;
  169. /// <summary>
  170. /// Gets the root folder.
  171. /// </summary>
  172. /// <value>The root folder.</value>
  173. public AggregateFolder RootFolder
  174. {
  175. get
  176. {
  177. LazyInitializer.EnsureInitialized(ref _rootFolder, ref _rootFolderInitialized, ref _rootFolderSyncLock, CreateRootFolder);
  178. return _rootFolder;
  179. }
  180. private set
  181. {
  182. _rootFolder = value;
  183. if (value == null)
  184. {
  185. _rootFolderInitialized = false;
  186. }
  187. }
  188. }
  189. private bool _internetProvidersEnabled;
  190. private bool _peopleImageFetchingEnabled;
  191. private string _itemsByNamePath;
  192. private void RecordConfigurationValues(ServerConfiguration configuration)
  193. {
  194. _itemsByNamePath = ConfigurationManager.ApplicationPaths.ItemsByNamePath;
  195. _internetProvidersEnabled = configuration.EnableInternetProviders;
  196. _peopleImageFetchingEnabled = configuration.InternetProviderExcludeTypes == null || !configuration.InternetProviderExcludeTypes.Contains(typeof(Person).Name, StringComparer.OrdinalIgnoreCase);
  197. }
  198. /// <summary>
  199. /// Configurations the updated.
  200. /// </summary>
  201. /// <param name="sender">The sender.</param>
  202. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  203. void ConfigurationUpdated(object sender, EventArgs e)
  204. {
  205. var config = ConfigurationManager.Configuration;
  206. // Figure out whether or not we should refresh people after the update is finished
  207. var refreshPeopleAfterUpdate = !_internetProvidersEnabled && config.EnableInternetProviders;
  208. // This is true if internet providers has just been turned on, or if People have just been removed from InternetProviderExcludeTypes
  209. if (!refreshPeopleAfterUpdate)
  210. {
  211. var newConfigurationFetchesPeopleImages = config.InternetProviderExcludeTypes == null || !config.InternetProviderExcludeTypes.Contains(typeof(Person).Name, StringComparer.OrdinalIgnoreCase);
  212. refreshPeopleAfterUpdate = newConfigurationFetchesPeopleImages && !_peopleImageFetchingEnabled;
  213. }
  214. var ibnPathChanged = !string.Equals(_itemsByNamePath, ConfigurationManager.ApplicationPaths.ItemsByNamePath);
  215. if (ibnPathChanged)
  216. {
  217. _itemsByName.Clear();
  218. }
  219. RecordConfigurationValues(config);
  220. Task.Run(() =>
  221. {
  222. // Any number of configuration settings could change the way the library is refreshed, so do that now
  223. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  224. if (refreshPeopleAfterUpdate)
  225. {
  226. _taskManager.CancelIfRunningAndQueue<PeopleValidationTask>();
  227. }
  228. });
  229. }
  230. /// <summary>
  231. /// Creates the library items cache.
  232. /// </summary>
  233. /// <returns>ConcurrentDictionary{GuidBaseItem}.</returns>
  234. private ConcurrentDictionary<Guid, BaseItem> CreateLibraryItemsCache()
  235. {
  236. var items = RootFolder.RecursiveChildren.ToList();
  237. items.Add(RootFolder);
  238. var specialFeatures = items.OfType<Movie>().SelectMany(i => i.SpecialFeatures).ToList();
  239. var localTrailers = items.SelectMany(i => i.LocalTrailers).ToList();
  240. items.AddRange(specialFeatures);
  241. items.AddRange(localTrailers);
  242. // Need to use DistinctBy Id because there could be multiple instances with the same id
  243. // due to sharing the default library
  244. var userRootFolders = _userManager.Users.Select(i => i.RootFolder)
  245. .DistinctBy(i => i.Id)
  246. .ToList();
  247. items.AddRange(userRootFolders);
  248. // Get all user collection folders
  249. var userFolders =
  250. _userManager.Users.SelectMany(i => i.RootFolder.Children)
  251. .Where(i => !(i is BasePluginFolder))
  252. .DistinctBy(i => i.Id)
  253. .ToList();
  254. items.AddRange(userFolders);
  255. return new ConcurrentDictionary<Guid, BaseItem>(items.ToDictionary(i => i.Id));
  256. }
  257. /// <summary>
  258. /// Updates the library cache.
  259. /// </summary>
  260. /// <param name="args">The <see cref="ChildrenChangedEventArgs"/> instance containing the event data.</param>
  261. private void UpdateLibraryCache(ChildrenChangedEventArgs args)
  262. {
  263. UpdateItemInLibraryCache(args.Folder);
  264. foreach (var item in args.ItemsAdded)
  265. {
  266. UpdateItemInLibraryCache(item);
  267. }
  268. foreach (var item in args.ItemsUpdated)
  269. {
  270. UpdateItemInLibraryCache(item);
  271. }
  272. }
  273. /// <summary>
  274. /// Updates the item in library cache.
  275. /// </summary>
  276. /// <param name="item">The item.</param>
  277. private void UpdateItemInLibraryCache(BaseItem item)
  278. {
  279. LibraryItemsCache.AddOrUpdate(item.Id, item, delegate { return item; });
  280. foreach (var trailer in item.LocalTrailers)
  281. {
  282. // Prevent access to foreach variable in closure
  283. var trailer1 = trailer;
  284. LibraryItemsCache.AddOrUpdate(trailer.Id, trailer, delegate { return trailer1; });
  285. }
  286. var movie = item as Movie;
  287. if (movie != null)
  288. {
  289. foreach (var special in movie.SpecialFeatures)
  290. {
  291. // Prevent access to foreach variable in closure
  292. var special1 = special;
  293. LibraryItemsCache.AddOrUpdate(special.Id, special, delegate { return special1; });
  294. }
  295. }
  296. }
  297. /// <summary>
  298. /// Resolves the item.
  299. /// </summary>
  300. /// <param name="args">The args.</param>
  301. /// <returns>BaseItem.</returns>
  302. public BaseItem ResolveItem(ItemResolveArgs args)
  303. {
  304. var item = EntityResolvers.Select(r => r.ResolvePath(args)).FirstOrDefault(i => i != null);
  305. if (item != null)
  306. {
  307. ResolverHelper.SetInitialItemValues(item, args);
  308. // Now handle the issue with posibly having the same item referenced from multiple physical
  309. // places within the library. Be sure we always end up with just one instance.
  310. if (item is IByReferenceItem)
  311. {
  312. item = GetOrAddByReferenceItem(item);
  313. }
  314. }
  315. return item;
  316. }
  317. /// <summary>
  318. /// Ensure supplied item has only one instance throughout
  319. /// </summary>
  320. /// <param name="item"></param>
  321. /// <returns>The proper instance to the item</returns>
  322. public BaseItem GetOrAddByReferenceItem(BaseItem item)
  323. {
  324. // Add this item to our list if not there already
  325. if (!ByReferenceItems.TryAdd(item.Id, item))
  326. {
  327. // Already there - return the existing reference
  328. item = ByReferenceItems[item.Id];
  329. }
  330. return item;
  331. }
  332. /// <summary>
  333. /// Resolves a path into a BaseItem
  334. /// </summary>
  335. /// <param name="path">The path.</param>
  336. /// <param name="parent">The parent.</param>
  337. /// <param name="fileInfo">The file info.</param>
  338. /// <returns>BaseItem.</returns>
  339. /// <exception cref="System.ArgumentNullException"></exception>
  340. public BaseItem ResolvePath(string path, Folder parent = null, WIN32_FIND_DATA? fileInfo = null)
  341. {
  342. if (string.IsNullOrEmpty(path))
  343. {
  344. throw new ArgumentNullException();
  345. }
  346. fileInfo = fileInfo ?? FileSystem.GetFileData(path);
  347. if (!fileInfo.HasValue)
  348. {
  349. return null;
  350. }
  351. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths)
  352. {
  353. Parent = parent,
  354. Path = path,
  355. FileInfo = fileInfo.Value
  356. };
  357. // Return null if ignore rules deem that we should do so
  358. if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(args)))
  359. {
  360. return null;
  361. }
  362. // Gather child folder and files
  363. if (args.IsDirectory)
  364. {
  365. var isPhysicalRoot = args.IsPhysicalRoot;
  366. // When resolving the root, we need it's grandchildren (children of user views)
  367. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  368. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, _logger, flattenFolderDepth: flattenFolderDepth, args: args, resolveShortcuts: isPhysicalRoot || args.IsVf);
  369. }
  370. // Check to see if we should resolve based on our contents
  371. if (args.IsDirectory && !ShouldResolvePathContents(args))
  372. {
  373. return null;
  374. }
  375. return ResolveItem(args);
  376. }
  377. /// <summary>
  378. /// Determines whether a path should be ignored based on its contents - called after the contents have been read
  379. /// </summary>
  380. /// <param name="args">The args.</param>
  381. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  382. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  383. {
  384. // Ignore any folders containing a file called .ignore
  385. return !args.ContainsFileSystemEntryByName(".ignore");
  386. }
  387. /// <summary>
  388. /// Resolves a set of files into a list of BaseItem
  389. /// </summary>
  390. /// <typeparam name="T"></typeparam>
  391. /// <param name="files">The files.</param>
  392. /// <param name="parent">The parent.</param>
  393. /// <returns>List{``0}.</returns>
  394. public List<T> ResolvePaths<T>(IEnumerable<WIN32_FIND_DATA> files, Folder parent)
  395. where T : BaseItem
  396. {
  397. var list = new List<T>();
  398. Parallel.ForEach(files, f =>
  399. {
  400. try
  401. {
  402. var item = ResolvePath(f.Path, parent, f) as T;
  403. if (item != null)
  404. {
  405. lock (list)
  406. {
  407. list.Add(item);
  408. }
  409. }
  410. }
  411. catch (Exception ex)
  412. {
  413. _logger.ErrorException("Error resolving path {0}", ex, f.Path);
  414. }
  415. });
  416. return list;
  417. }
  418. /// <summary>
  419. /// Creates the root media folder
  420. /// </summary>
  421. /// <returns>AggregateFolder.</returns>
  422. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  423. public AggregateFolder CreateRootFolder()
  424. {
  425. var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
  426. var rootFolder = RetrieveItem(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(rootFolderPath);
  427. // Add in the plug-in folders
  428. foreach (var child in PluginFolderCreators)
  429. {
  430. rootFolder.AddVirtualChild(child.GetFolder());
  431. }
  432. return rootFolder;
  433. }
  434. /// <summary>
  435. /// Gets the user root folder.
  436. /// </summary>
  437. /// <param name="userRootPath">The user root path.</param>
  438. /// <returns>UserRootFolder.</returns>
  439. public UserRootFolder GetUserRootFolder(string userRootPath)
  440. {
  441. return _userRootFolders.GetOrAdd(userRootPath, key => RetrieveItem(userRootPath.GetMBId(typeof(UserRootFolder))) as UserRootFolder ?? (UserRootFolder)ResolvePath(userRootPath));
  442. }
  443. /// <summary>
  444. /// Gets a Person
  445. /// </summary>
  446. /// <param name="name">The name.</param>
  447. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  448. /// <returns>Task{Person}.</returns>
  449. public Task<Person> GetPerson(string name, bool allowSlowProviders = false)
  450. {
  451. return GetPerson(name, CancellationToken.None, allowSlowProviders);
  452. }
  453. /// <summary>
  454. /// Gets a Person
  455. /// </summary>
  456. /// <param name="name">The name.</param>
  457. /// <param name="cancellationToken">The cancellation token.</param>
  458. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  459. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  460. /// <returns>Task{Person}.</returns>
  461. private Task<Person> GetPerson(string name, CancellationToken cancellationToken, bool allowSlowProviders = false, bool forceCreation = false)
  462. {
  463. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name, cancellationToken, allowSlowProviders, forceCreation);
  464. }
  465. /// <summary>
  466. /// Gets a Studio
  467. /// </summary>
  468. /// <param name="name">The name.</param>
  469. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  470. /// <returns>Task{Studio}.</returns>
  471. public Task<Studio> GetStudio(string name, bool allowSlowProviders = false)
  472. {
  473. return GetItemByName<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name, CancellationToken.None, allowSlowProviders);
  474. }
  475. /// <summary>
  476. /// Gets a Genre
  477. /// </summary>
  478. /// <param name="name">The name.</param>
  479. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  480. /// <returns>Task{Genre}.</returns>
  481. public Task<Genre> GetGenre(string name, bool allowSlowProviders = false)
  482. {
  483. return GetItemByName<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name, CancellationToken.None, allowSlowProviders);
  484. }
  485. /// <summary>
  486. /// Gets a Genre
  487. /// </summary>
  488. /// <param name="name">The name.</param>
  489. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  490. /// <returns>Task{Genre}.</returns>
  491. public Task<Artist> GetArtist(string name, bool allowSlowProviders = false)
  492. {
  493. return GetArtist(name, CancellationToken.None, allowSlowProviders);
  494. }
  495. /// <summary>
  496. /// Gets the artist.
  497. /// </summary>
  498. /// <param name="name">The name.</param>
  499. /// <param name="cancellationToken">The cancellation token.</param>
  500. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  501. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  502. /// <returns>Task{Artist}.</returns>
  503. private Task<Artist> GetArtist(string name, CancellationToken cancellationToken, bool allowSlowProviders = false, bool forceCreation = false)
  504. {
  505. return GetItemByName<Artist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name, cancellationToken, allowSlowProviders, forceCreation);
  506. }
  507. /// <summary>
  508. /// The us culture
  509. /// </summary>
  510. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  511. /// <summary>
  512. /// Gets a Year
  513. /// </summary>
  514. /// <param name="value">The value.</param>
  515. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  516. /// <returns>Task{Year}.</returns>
  517. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  518. public Task<Year> GetYear(int value, bool allowSlowProviders = false)
  519. {
  520. if (value <= 0)
  521. {
  522. throw new ArgumentOutOfRangeException();
  523. }
  524. return GetItemByName<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture), CancellationToken.None, allowSlowProviders);
  525. }
  526. /// <summary>
  527. /// The images by name item cache
  528. /// </summary>
  529. private readonly ConcurrentDictionary<string, BaseItem> _itemsByName = new ConcurrentDictionary<string, BaseItem>(StringComparer.OrdinalIgnoreCase);
  530. /// <summary>
  531. /// Generically retrieves an IBN item
  532. /// </summary>
  533. /// <typeparam name="T"></typeparam>
  534. /// <param name="path">The path.</param>
  535. /// <param name="name">The name.</param>
  536. /// <param name="cancellationToken">The cancellation token.</param>
  537. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  538. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  539. /// <returns>Task{``0}.</returns>
  540. /// <exception cref="System.ArgumentNullException">
  541. /// </exception>
  542. private async Task<T> GetItemByName<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true, bool forceCreation = false)
  543. where T : BaseItem, new()
  544. {
  545. if (string.IsNullOrEmpty(path))
  546. {
  547. throw new ArgumentNullException();
  548. }
  549. if (string.IsNullOrEmpty(name))
  550. {
  551. throw new ArgumentNullException();
  552. }
  553. var key = Path.Combine(path, FileSystem.GetValidFilename(name));
  554. BaseItem obj;
  555. if (forceCreation || !_itemsByName.TryGetValue(key, out obj))
  556. {
  557. obj = await CreateItemByName<T>(path, name, cancellationToken, allowSlowProviders).ConfigureAwait(false);
  558. _itemsByName.AddOrUpdate(key, obj, (keyName, oldValue) => obj);
  559. }
  560. return obj as T;
  561. }
  562. /// <summary>
  563. /// Creates an IBN item based on a given path
  564. /// </summary>
  565. /// <typeparam name="T"></typeparam>
  566. /// <param name="path">The path.</param>
  567. /// <param name="name">The name.</param>
  568. /// <param name="cancellationToken">The cancellation token.</param>
  569. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  570. /// <returns>Task{``0}.</returns>
  571. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  572. private async Task<T> CreateItemByName<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  573. where T : BaseItem, new()
  574. {
  575. cancellationToken.ThrowIfCancellationRequested();
  576. _logger.Debug("Getting {0}: {1}", typeof(T).Name, name);
  577. path = Path.Combine(path, FileSystem.GetValidFilename(name));
  578. var fileInfo = FileSystem.GetFileData(path);
  579. var isNew = false;
  580. if (!fileInfo.HasValue)
  581. {
  582. Directory.CreateDirectory(path);
  583. fileInfo = FileSystem.GetFileData(path);
  584. if (!fileInfo.HasValue)
  585. {
  586. throw new IOException("Path not created: " + path);
  587. }
  588. isNew = true;
  589. }
  590. cancellationToken.ThrowIfCancellationRequested();
  591. var id = path.GetMBId(typeof(T));
  592. var item = RetrieveItem(id) as T;
  593. if (item == null)
  594. {
  595. item = new T
  596. {
  597. Name = name,
  598. Id = id,
  599. DateCreated = fileInfo.Value.CreationTimeUtc,
  600. DateModified = fileInfo.Value.LastWriteTimeUtc,
  601. Path = path
  602. };
  603. isNew = true;
  604. }
  605. cancellationToken.ThrowIfCancellationRequested();
  606. // Set this now so we don't cause additional file system access during provider executions
  607. item.ResetResolveArgs(fileInfo);
  608. await item.RefreshMetadata(cancellationToken, isNew, allowSlowProviders: allowSlowProviders).ConfigureAwait(false);
  609. cancellationToken.ThrowIfCancellationRequested();
  610. return item;
  611. }
  612. /// <summary>
  613. /// Validate and refresh the People sub-set of the IBN.
  614. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  615. /// </summary>
  616. /// <param name="cancellationToken">The cancellation token.</param>
  617. /// <param name="progress">The progress.</param>
  618. /// <returns>Task.</returns>
  619. public async Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  620. {
  621. const int maxTasks = 25;
  622. var tasks = new List<Task>();
  623. var includedPersonTypes = new[] { PersonType.Actor, PersonType.Director, PersonType.GuestStar, PersonType.Writer, PersonType.Director, PersonType.Producer };
  624. var people = RootFolder.RecursiveChildren
  625. .Where(c => c.People != null)
  626. .SelectMany(c => c.People.Where(p => includedPersonTypes.Contains(p.Type)))
  627. .DistinctBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
  628. .ToList();
  629. var numComplete = 0;
  630. foreach (var person in people)
  631. {
  632. if (tasks.Count > maxTasks)
  633. {
  634. await Task.WhenAll(tasks).ConfigureAwait(false);
  635. tasks.Clear();
  636. // Safe cancellation point, when there are no pending tasks
  637. cancellationToken.ThrowIfCancellationRequested();
  638. }
  639. // Avoid accessing the foreach variable within the closure
  640. var currentPerson = person;
  641. tasks.Add(Task.Run(async () =>
  642. {
  643. cancellationToken.ThrowIfCancellationRequested();
  644. try
  645. {
  646. await GetPerson(currentPerson.Name, cancellationToken, true, true).ConfigureAwait(false);
  647. }
  648. catch (IOException ex)
  649. {
  650. _logger.ErrorException("Error validating IBN entry {0}", ex, currentPerson.Name);
  651. }
  652. // Update progress
  653. lock (progress)
  654. {
  655. numComplete++;
  656. double percent = numComplete;
  657. percent /= people.Count;
  658. progress.Report(100 * percent);
  659. }
  660. }));
  661. }
  662. await Task.WhenAll(tasks).ConfigureAwait(false);
  663. progress.Report(100);
  664. _logger.Info("People validation complete");
  665. }
  666. public async Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  667. {
  668. const int maxTasks = 25;
  669. var tasks = new List<Task>();
  670. var artists = RootFolder.RecursiveChildren
  671. .OfType<Audio>()
  672. .SelectMany(c =>
  673. {
  674. var list = new List<string>();
  675. if (!string.IsNullOrEmpty(c.AlbumArtist))
  676. {
  677. list.Add(c.AlbumArtist);
  678. }
  679. if (!string.IsNullOrEmpty(c.Artist))
  680. {
  681. list.Add(c.Artist);
  682. }
  683. return list;
  684. })
  685. .Distinct(StringComparer.OrdinalIgnoreCase)
  686. .ToList();
  687. var numComplete = 0;
  688. foreach (var artist in artists)
  689. {
  690. if (tasks.Count > maxTasks)
  691. {
  692. await Task.WhenAll(tasks).ConfigureAwait(false);
  693. tasks.Clear();
  694. // Safe cancellation point, when there are no pending tasks
  695. cancellationToken.ThrowIfCancellationRequested();
  696. }
  697. // Avoid accessing the foreach variable within the closure
  698. var currentArtist = artist;
  699. tasks.Add(Task.Run(async () =>
  700. {
  701. cancellationToken.ThrowIfCancellationRequested();
  702. try
  703. {
  704. await GetArtist(currentArtist, cancellationToken, true, true).ConfigureAwait(false);
  705. }
  706. catch (IOException ex)
  707. {
  708. _logger.ErrorException("Error validating Artist {0}", ex, currentArtist);
  709. }
  710. // Update progress
  711. lock (progress)
  712. {
  713. numComplete++;
  714. double percent = numComplete;
  715. percent /= artists.Count;
  716. progress.Report(100 * percent);
  717. }
  718. }));
  719. }
  720. await Task.WhenAll(tasks).ConfigureAwait(false);
  721. progress.Report(100);
  722. _logger.Info("Artist validation complete");
  723. }
  724. /// <summary>
  725. /// Reloads the root media folder
  726. /// </summary>
  727. /// <param name="progress">The progress.</param>
  728. /// <param name="cancellationToken">The cancellation token.</param>
  729. /// <returns>Task.</returns>
  730. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  731. {
  732. // Just run the scheduled task so that the user can see it
  733. return Task.Run(() => _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>());
  734. }
  735. /// <summary>
  736. /// Validates the media library internal.
  737. /// </summary>
  738. /// <param name="progress">The progress.</param>
  739. /// <param name="cancellationToken">The cancellation token.</param>
  740. /// <returns>Task.</returns>
  741. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  742. {
  743. _logger.Info("Validating media library");
  744. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  745. // Start by just validating the children of the root, but go no further
  746. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false);
  747. foreach (var folder in _userManager.Users.Select(u => u.RootFolder).Distinct())
  748. {
  749. await ValidateCollectionFolders(folder, cancellationToken).ConfigureAwait(false);
  750. }
  751. var innerProgress = new ActionableProgress<double>();
  752. innerProgress.RegisterAction(pct => progress.Report(pct * .8));
  753. // Now validate the entire media library
  754. await RootFolder.ValidateChildren(innerProgress, cancellationToken, recursive: true).ConfigureAwait(false);
  755. innerProgress = new ActionableProgress<double>();
  756. innerProgress.RegisterAction(pct => progress.Report(80 + pct * .2));
  757. await ValidateArtists(cancellationToken, innerProgress);
  758. progress.Report(100);
  759. }
  760. /// <summary>
  761. /// Validates only the collection folders for a User and goes no further
  762. /// </summary>
  763. /// <param name="userRootFolder">The user root folder.</param>
  764. /// <param name="cancellationToken">The cancellation token.</param>
  765. /// <returns>Task.</returns>
  766. private async Task ValidateCollectionFolders(UserRootFolder userRootFolder, CancellationToken cancellationToken)
  767. {
  768. _logger.Info("Validating collection folders within {0}", userRootFolder.Path);
  769. await userRootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  770. cancellationToken.ThrowIfCancellationRequested();
  771. await userRootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false).ConfigureAwait(false);
  772. }
  773. /// <summary>
  774. /// Gets the default view.
  775. /// </summary>
  776. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  777. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  778. {
  779. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  780. }
  781. /// <summary>
  782. /// Gets the view.
  783. /// </summary>
  784. /// <param name="user">The user.</param>
  785. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  786. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  787. {
  788. return GetView(user.RootFolderPath);
  789. }
  790. /// <summary>
  791. /// Gets the view.
  792. /// </summary>
  793. /// <param name="path">The path.</param>
  794. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  795. private IEnumerable<VirtualFolderInfo> GetView(string path)
  796. {
  797. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  798. .Select(dir => new VirtualFolderInfo
  799. {
  800. Name = Path.GetFileName(dir),
  801. Locations = Directory.EnumerateFiles(dir, "*.lnk", SearchOption.TopDirectoryOnly).Select(FileSystem.ResolveShortcut).OrderBy(i => i).ToList()
  802. });
  803. }
  804. /// <summary>
  805. /// Gets the item by id.
  806. /// </summary>
  807. /// <param name="id">The id.</param>
  808. /// <returns>BaseItem.</returns>
  809. /// <exception cref="System.ArgumentNullException">id</exception>
  810. public BaseItem GetItemById(Guid id)
  811. {
  812. if (id == Guid.Empty)
  813. {
  814. throw new ArgumentNullException("id");
  815. }
  816. BaseItem item;
  817. LibraryItemsCache.TryGetValue(id, out item);
  818. return item;
  819. }
  820. /// <summary>
  821. /// Gets the intros.
  822. /// </summary>
  823. /// <param name="item">The item.</param>
  824. /// <param name="user">The user.</param>
  825. /// <returns>IEnumerable{System.String}.</returns>
  826. public IEnumerable<string> GetIntros(BaseItem item, User user)
  827. {
  828. return IntroProviders.SelectMany(i => i.GetIntros(item, user));
  829. }
  830. /// <summary>
  831. /// Sorts the specified sort by.
  832. /// </summary>
  833. /// <param name="items">The items.</param>
  834. /// <param name="user">The user.</param>
  835. /// <param name="sortBy">The sort by.</param>
  836. /// <param name="sortOrder">The sort order.</param>
  837. /// <returns>IEnumerable{BaseItem}.</returns>
  838. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  839. {
  840. var isFirst = true;
  841. IOrderedEnumerable<BaseItem> orderedItems = null;
  842. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  843. {
  844. if (isFirst)
  845. {
  846. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  847. }
  848. else
  849. {
  850. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  851. }
  852. isFirst = false;
  853. }
  854. return orderedItems ?? items;
  855. }
  856. /// <summary>
  857. /// Gets the comparer.
  858. /// </summary>
  859. /// <param name="name">The name.</param>
  860. /// <param name="user">The user.</param>
  861. /// <returns>IBaseItemComparer.</returns>
  862. private IBaseItemComparer GetComparer(string name, User user)
  863. {
  864. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  865. if (comparer != null)
  866. {
  867. // If it requires a user, create a new one, and assign the user
  868. if (comparer is IUserBaseItemComparer)
  869. {
  870. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  871. userComparer.User = user;
  872. userComparer.UserManager = _userManager;
  873. userComparer.UserDataRepository = _userDataRepository;
  874. return userComparer;
  875. }
  876. }
  877. return comparer;
  878. }
  879. /// <summary>
  880. /// Saves the item.
  881. /// </summary>
  882. /// <param name="item">The item.</param>
  883. /// <param name="cancellationToken">The cancellation token.</param>
  884. /// <returns>Task.</returns>
  885. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  886. {
  887. return ItemRepository.SaveItem(item, cancellationToken);
  888. }
  889. /// <summary>
  890. /// Retrieves the item.
  891. /// </summary>
  892. /// <param name="id">The id.</param>
  893. /// <returns>Task{BaseItem}.</returns>
  894. public BaseItem RetrieveItem(Guid id)
  895. {
  896. return ItemRepository.RetrieveItem(id);
  897. }
  898. /// <summary>
  899. /// Saves the children.
  900. /// </summary>
  901. /// <param name="id">The id.</param>
  902. /// <param name="children">The children.</param>
  903. /// <param name="cancellationToken">The cancellation token.</param>
  904. /// <returns>Task.</returns>
  905. public Task SaveChildren(Guid id, IEnumerable<BaseItem> children, CancellationToken cancellationToken)
  906. {
  907. return ItemRepository.SaveChildren(id, children, cancellationToken);
  908. }
  909. /// <summary>
  910. /// Retrieves the children.
  911. /// </summary>
  912. /// <param name="parent">The parent.</param>
  913. /// <returns>IEnumerable{BaseItem}.</returns>
  914. public IEnumerable<BaseItem> RetrieveChildren(Folder parent)
  915. {
  916. return ItemRepository.RetrieveChildren(parent);
  917. }
  918. }
  919. }