LibraryManager.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  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. var themeSongs = items.SelectMany(i => i.ThemeSongs).ToList();
  241. items.AddRange(specialFeatures);
  242. items.AddRange(localTrailers);
  243. items.AddRange(themeSongs);
  244. // Need to use DistinctBy Id because there could be multiple instances with the same id
  245. // due to sharing the default library
  246. var userRootFolders = _userManager.Users.Select(i => i.RootFolder)
  247. .DistinctBy(i => i.Id)
  248. .ToList();
  249. items.AddRange(userRootFolders);
  250. // Get all user collection folders
  251. var userFolders =
  252. _userManager.Users.SelectMany(i => i.RootFolder.Children)
  253. .Where(i => !(i is BasePluginFolder))
  254. .DistinctBy(i => i.Id)
  255. .ToList();
  256. items.AddRange(userFolders);
  257. return new ConcurrentDictionary<Guid, BaseItem>(items.ToDictionary(i => i.Id));
  258. }
  259. /// <summary>
  260. /// Updates the library cache.
  261. /// </summary>
  262. /// <param name="args">The <see cref="ChildrenChangedEventArgs"/> instance containing the event data.</param>
  263. private void UpdateLibraryCache(ChildrenChangedEventArgs args)
  264. {
  265. UpdateItemInLibraryCache(args.Folder);
  266. foreach (var item in args.ItemsAdded)
  267. {
  268. UpdateItemInLibraryCache(item);
  269. }
  270. foreach (var item in args.ItemsUpdated)
  271. {
  272. UpdateItemInLibraryCache(item);
  273. }
  274. }
  275. /// <summary>
  276. /// Updates the item in library cache.
  277. /// </summary>
  278. /// <param name="item">The item.</param>
  279. private void UpdateItemInLibraryCache(BaseItem item)
  280. {
  281. LibraryItemsCache.AddOrUpdate(item.Id, item, delegate { return item; });
  282. foreach (var subItem in item.LocalTrailers)
  283. {
  284. // Prevent access to foreach variable in closure
  285. var trailer1 = subItem;
  286. LibraryItemsCache.AddOrUpdate(subItem.Id, subItem, delegate { return trailer1; });
  287. }
  288. foreach (var subItem in item.ThemeSongs)
  289. {
  290. // Prevent access to foreach variable in closure
  291. var trailer1 = subItem;
  292. LibraryItemsCache.AddOrUpdate(subItem.Id, subItem, delegate { return trailer1; });
  293. }
  294. var movie = item as Movie;
  295. if (movie != null)
  296. {
  297. foreach (var subItem in movie.SpecialFeatures)
  298. {
  299. // Prevent access to foreach variable in closure
  300. var special1 = subItem;
  301. LibraryItemsCache.AddOrUpdate(subItem.Id, subItem, delegate { return special1; });
  302. }
  303. }
  304. }
  305. /// <summary>
  306. /// Resolves the item.
  307. /// </summary>
  308. /// <param name="args">The args.</param>
  309. /// <returns>BaseItem.</returns>
  310. public BaseItem ResolveItem(ItemResolveArgs args)
  311. {
  312. var item = EntityResolvers.Select(r => r.ResolvePath(args)).FirstOrDefault(i => i != null);
  313. if (item != null)
  314. {
  315. ResolverHelper.SetInitialItemValues(item, args);
  316. // Now handle the issue with posibly having the same item referenced from multiple physical
  317. // places within the library. Be sure we always end up with just one instance.
  318. if (item is IByReferenceItem)
  319. {
  320. item = GetOrAddByReferenceItem(item);
  321. }
  322. }
  323. return item;
  324. }
  325. /// <summary>
  326. /// Ensure supplied item has only one instance throughout
  327. /// </summary>
  328. /// <param name="item"></param>
  329. /// <returns>The proper instance to the item</returns>
  330. public BaseItem GetOrAddByReferenceItem(BaseItem item)
  331. {
  332. // Add this item to our list if not there already
  333. if (!ByReferenceItems.TryAdd(item.Id, item))
  334. {
  335. // Already there - return the existing reference
  336. item = ByReferenceItems[item.Id];
  337. }
  338. return item;
  339. }
  340. /// <summary>
  341. /// Resolves a path into a BaseItem
  342. /// </summary>
  343. /// <param name="path">The path.</param>
  344. /// <param name="parent">The parent.</param>
  345. /// <param name="fileInfo">The file info.</param>
  346. /// <returns>BaseItem.</returns>
  347. /// <exception cref="System.ArgumentNullException"></exception>
  348. public BaseItem ResolvePath(string path, Folder parent = null, FileSystemInfo fileInfo = null)
  349. {
  350. if (string.IsNullOrEmpty(path))
  351. {
  352. throw new ArgumentNullException();
  353. }
  354. fileInfo = fileInfo ?? FileSystem.GetFileSystemInfo(path);
  355. if (!fileInfo.Exists)
  356. {
  357. return null;
  358. }
  359. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths)
  360. {
  361. Parent = parent,
  362. Path = path,
  363. FileInfo = fileInfo
  364. };
  365. // Return null if ignore rules deem that we should do so
  366. if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(args)))
  367. {
  368. return null;
  369. }
  370. // Gather child folder and files
  371. if (args.IsDirectory)
  372. {
  373. var isPhysicalRoot = args.IsPhysicalRoot;
  374. // When resolving the root, we need it's grandchildren (children of user views)
  375. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  376. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, _logger, flattenFolderDepth: flattenFolderDepth, args: args, resolveShortcuts: isPhysicalRoot || args.IsVf);
  377. }
  378. // Check to see if we should resolve based on our contents
  379. if (args.IsDirectory && !ShouldResolvePathContents(args))
  380. {
  381. return null;
  382. }
  383. return ResolveItem(args);
  384. }
  385. /// <summary>
  386. /// Determines whether a path should be ignored based on its contents - called after the contents have been read
  387. /// </summary>
  388. /// <param name="args">The args.</param>
  389. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  390. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  391. {
  392. // Ignore any folders containing a file called .ignore
  393. return !args.ContainsFileSystemEntryByName(".ignore");
  394. }
  395. /// <summary>
  396. /// Resolves a set of files into a list of BaseItem
  397. /// </summary>
  398. /// <typeparam name="T"></typeparam>
  399. /// <param name="files">The files.</param>
  400. /// <param name="parent">The parent.</param>
  401. /// <returns>List{``0}.</returns>
  402. public List<T> ResolvePaths<T>(IEnumerable<FileSystemInfo> files, Folder parent)
  403. where T : BaseItem
  404. {
  405. var list = new List<T>();
  406. Parallel.ForEach(files, f =>
  407. {
  408. try
  409. {
  410. var item = ResolvePath(f.FullName, parent, f) as T;
  411. if (item != null)
  412. {
  413. lock (list)
  414. {
  415. list.Add(item);
  416. }
  417. }
  418. }
  419. catch (Exception ex)
  420. {
  421. _logger.ErrorException("Error resolving path {0}", ex, f.FullName);
  422. }
  423. });
  424. return list;
  425. }
  426. /// <summary>
  427. /// Creates the root media folder
  428. /// </summary>
  429. /// <returns>AggregateFolder.</returns>
  430. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  431. public AggregateFolder CreateRootFolder()
  432. {
  433. var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
  434. var rootFolder = RetrieveItem(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(rootFolderPath);
  435. // Add in the plug-in folders
  436. foreach (var child in PluginFolderCreators)
  437. {
  438. rootFolder.AddVirtualChild(child.GetFolder());
  439. }
  440. return rootFolder;
  441. }
  442. /// <summary>
  443. /// Gets the user root folder.
  444. /// </summary>
  445. /// <param name="userRootPath">The user root path.</param>
  446. /// <returns>UserRootFolder.</returns>
  447. public UserRootFolder GetUserRootFolder(string userRootPath)
  448. {
  449. return _userRootFolders.GetOrAdd(userRootPath, key => RetrieveItem(userRootPath.GetMBId(typeof(UserRootFolder))) as UserRootFolder ?? (UserRootFolder)ResolvePath(userRootPath));
  450. }
  451. /// <summary>
  452. /// Gets a Person
  453. /// </summary>
  454. /// <param name="name">The name.</param>
  455. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  456. /// <returns>Task{Person}.</returns>
  457. public Task<Person> GetPerson(string name, bool allowSlowProviders = false)
  458. {
  459. return GetPerson(name, CancellationToken.None, allowSlowProviders);
  460. }
  461. /// <summary>
  462. /// Gets a Person
  463. /// </summary>
  464. /// <param name="name">The name.</param>
  465. /// <param name="cancellationToken">The cancellation token.</param>
  466. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  467. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  468. /// <returns>Task{Person}.</returns>
  469. private Task<Person> GetPerson(string name, CancellationToken cancellationToken, bool allowSlowProviders = false, bool forceCreation = false)
  470. {
  471. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name, cancellationToken, allowSlowProviders, forceCreation);
  472. }
  473. /// <summary>
  474. /// Gets a Studio
  475. /// </summary>
  476. /// <param name="name">The name.</param>
  477. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  478. /// <returns>Task{Studio}.</returns>
  479. public Task<Studio> GetStudio(string name, bool allowSlowProviders = false)
  480. {
  481. return GetItemByName<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name, CancellationToken.None, allowSlowProviders);
  482. }
  483. /// <summary>
  484. /// Gets a Genre
  485. /// </summary>
  486. /// <param name="name">The name.</param>
  487. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  488. /// <returns>Task{Genre}.</returns>
  489. public Task<Genre> GetGenre(string name, bool allowSlowProviders = false)
  490. {
  491. return GetItemByName<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name, CancellationToken.None, allowSlowProviders);
  492. }
  493. /// <summary>
  494. /// Gets a Genre
  495. /// </summary>
  496. /// <param name="name">The name.</param>
  497. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  498. /// <returns>Task{Genre}.</returns>
  499. public Task<Artist> GetArtist(string name, bool allowSlowProviders = false)
  500. {
  501. return GetArtist(name, CancellationToken.None, allowSlowProviders);
  502. }
  503. /// <summary>
  504. /// Gets the artist.
  505. /// </summary>
  506. /// <param name="name">The name.</param>
  507. /// <param name="cancellationToken">The cancellation token.</param>
  508. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  509. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  510. /// <returns>Task{Artist}.</returns>
  511. private Task<Artist> GetArtist(string name, CancellationToken cancellationToken, bool allowSlowProviders = false, bool forceCreation = false)
  512. {
  513. return GetItemByName<Artist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name, cancellationToken, allowSlowProviders, forceCreation);
  514. }
  515. /// <summary>
  516. /// The us culture
  517. /// </summary>
  518. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  519. /// <summary>
  520. /// Gets a Year
  521. /// </summary>
  522. /// <param name="value">The value.</param>
  523. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  524. /// <returns>Task{Year}.</returns>
  525. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  526. public Task<Year> GetYear(int value, bool allowSlowProviders = false)
  527. {
  528. if (value <= 0)
  529. {
  530. throw new ArgumentOutOfRangeException();
  531. }
  532. return GetItemByName<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture), CancellationToken.None, allowSlowProviders);
  533. }
  534. /// <summary>
  535. /// The images by name item cache
  536. /// </summary>
  537. private readonly ConcurrentDictionary<string, BaseItem> _itemsByName = new ConcurrentDictionary<string, BaseItem>(StringComparer.OrdinalIgnoreCase);
  538. /// <summary>
  539. /// Generically retrieves an IBN item
  540. /// </summary>
  541. /// <typeparam name="T"></typeparam>
  542. /// <param name="path">The path.</param>
  543. /// <param name="name">The name.</param>
  544. /// <param name="cancellationToken">The cancellation token.</param>
  545. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  546. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  547. /// <returns>Task{``0}.</returns>
  548. /// <exception cref="System.ArgumentNullException">
  549. /// </exception>
  550. private async Task<T> GetItemByName<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true, bool forceCreation = false)
  551. where T : BaseItem, new()
  552. {
  553. if (string.IsNullOrEmpty(path))
  554. {
  555. throw new ArgumentNullException();
  556. }
  557. if (string.IsNullOrEmpty(name))
  558. {
  559. throw new ArgumentNullException();
  560. }
  561. var key = Path.Combine(path, FileSystem.GetValidFilename(name));
  562. BaseItem obj;
  563. if (forceCreation || !_itemsByName.TryGetValue(key, out obj))
  564. {
  565. obj = await CreateItemByName<T>(path, name, cancellationToken, allowSlowProviders).ConfigureAwait(false);
  566. _itemsByName.AddOrUpdate(key, obj, (keyName, oldValue) => obj);
  567. }
  568. return obj as T;
  569. }
  570. /// <summary>
  571. /// Creates an IBN item based on a given path
  572. /// </summary>
  573. /// <typeparam name="T"></typeparam>
  574. /// <param name="path">The path.</param>
  575. /// <param name="name">The name.</param>
  576. /// <param name="cancellationToken">The cancellation token.</param>
  577. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  578. /// <returns>Task{``0}.</returns>
  579. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  580. private async Task<T> CreateItemByName<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  581. where T : BaseItem, new()
  582. {
  583. cancellationToken.ThrowIfCancellationRequested();
  584. _logger.Debug("Getting {0}: {1}", typeof(T).Name, name);
  585. path = Path.Combine(path, FileSystem.GetValidFilename(name));
  586. var fileInfo = new DirectoryInfo(path);
  587. var isNew = false;
  588. if (!fileInfo.Exists)
  589. {
  590. Directory.CreateDirectory(path);
  591. fileInfo = new DirectoryInfo(path);
  592. if (!fileInfo.Exists)
  593. {
  594. throw new IOException("Path not created: " + path);
  595. }
  596. isNew = true;
  597. }
  598. cancellationToken.ThrowIfCancellationRequested();
  599. var id = path.GetMBId(typeof(T));
  600. var item = RetrieveItem(id) as T;
  601. if (item == null)
  602. {
  603. item = new T
  604. {
  605. Name = name,
  606. Id = id,
  607. DateCreated = fileInfo.CreationTimeUtc,
  608. DateModified = fileInfo.LastWriteTimeUtc,
  609. Path = path
  610. };
  611. isNew = true;
  612. }
  613. cancellationToken.ThrowIfCancellationRequested();
  614. // Set this now so we don't cause additional file system access during provider executions
  615. item.ResetResolveArgs(fileInfo);
  616. await item.RefreshMetadata(cancellationToken, isNew, allowSlowProviders: allowSlowProviders).ConfigureAwait(false);
  617. cancellationToken.ThrowIfCancellationRequested();
  618. return item;
  619. }
  620. /// <summary>
  621. /// Validate and refresh the People sub-set of the IBN.
  622. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  623. /// </summary>
  624. /// <param name="cancellationToken">The cancellation token.</param>
  625. /// <param name="progress">The progress.</param>
  626. /// <returns>Task.</returns>
  627. public async Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  628. {
  629. const int maxTasks = 25;
  630. var tasks = new List<Task>();
  631. var includedPersonTypes = new[] { PersonType.Actor, PersonType.Director, PersonType.GuestStar, PersonType.Writer, PersonType.Director, PersonType.Producer };
  632. var people = RootFolder.RecursiveChildren
  633. .Where(c => c.People != null)
  634. .SelectMany(c => c.People.Where(p => includedPersonTypes.Contains(p.Type)))
  635. .DistinctBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
  636. .ToList();
  637. var numComplete = 0;
  638. foreach (var person in people)
  639. {
  640. if (tasks.Count > maxTasks)
  641. {
  642. await Task.WhenAll(tasks).ConfigureAwait(false);
  643. tasks.Clear();
  644. // Safe cancellation point, when there are no pending tasks
  645. cancellationToken.ThrowIfCancellationRequested();
  646. }
  647. // Avoid accessing the foreach variable within the closure
  648. var currentPerson = person;
  649. tasks.Add(Task.Run(async () =>
  650. {
  651. cancellationToken.ThrowIfCancellationRequested();
  652. try
  653. {
  654. await GetPerson(currentPerson.Name, cancellationToken, true, true).ConfigureAwait(false);
  655. }
  656. catch (IOException ex)
  657. {
  658. _logger.ErrorException("Error validating IBN entry {0}", ex, currentPerson.Name);
  659. }
  660. // Update progress
  661. lock (progress)
  662. {
  663. numComplete++;
  664. double percent = numComplete;
  665. percent /= people.Count;
  666. progress.Report(100 * percent);
  667. }
  668. }));
  669. }
  670. await Task.WhenAll(tasks).ConfigureAwait(false);
  671. progress.Report(100);
  672. _logger.Info("People validation complete");
  673. }
  674. public async Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  675. {
  676. const int maxTasks = 25;
  677. var tasks = new List<Task>();
  678. var artists = RootFolder.RecursiveChildren
  679. .OfType<Audio>()
  680. .SelectMany(c =>
  681. {
  682. var list = new List<string>();
  683. if (!string.IsNullOrEmpty(c.AlbumArtist))
  684. {
  685. list.Add(c.AlbumArtist);
  686. }
  687. if (!string.IsNullOrEmpty(c.Artist))
  688. {
  689. list.Add(c.Artist);
  690. }
  691. return list;
  692. })
  693. .Distinct(StringComparer.OrdinalIgnoreCase)
  694. .ToList();
  695. var numComplete = 0;
  696. foreach (var artist in artists)
  697. {
  698. if (tasks.Count > maxTasks)
  699. {
  700. await Task.WhenAll(tasks).ConfigureAwait(false);
  701. tasks.Clear();
  702. // Safe cancellation point, when there are no pending tasks
  703. cancellationToken.ThrowIfCancellationRequested();
  704. }
  705. // Avoid accessing the foreach variable within the closure
  706. var currentArtist = artist;
  707. tasks.Add(Task.Run(async () =>
  708. {
  709. cancellationToken.ThrowIfCancellationRequested();
  710. try
  711. {
  712. await GetArtist(currentArtist, cancellationToken, true, true).ConfigureAwait(false);
  713. }
  714. catch (IOException ex)
  715. {
  716. _logger.ErrorException("Error validating Artist {0}", ex, currentArtist);
  717. }
  718. // Update progress
  719. lock (progress)
  720. {
  721. numComplete++;
  722. double percent = numComplete;
  723. percent /= artists.Count;
  724. progress.Report(100 * percent);
  725. }
  726. }));
  727. }
  728. await Task.WhenAll(tasks).ConfigureAwait(false);
  729. progress.Report(100);
  730. _logger.Info("Artist validation complete");
  731. }
  732. /// <summary>
  733. /// Reloads the root media folder
  734. /// </summary>
  735. /// <param name="progress">The progress.</param>
  736. /// <param name="cancellationToken">The cancellation token.</param>
  737. /// <returns>Task.</returns>
  738. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  739. {
  740. // Just run the scheduled task so that the user can see it
  741. return Task.Run(() => _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>());
  742. }
  743. /// <summary>
  744. /// Validates the media library internal.
  745. /// </summary>
  746. /// <param name="progress">The progress.</param>
  747. /// <param name="cancellationToken">The cancellation token.</param>
  748. /// <returns>Task.</returns>
  749. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  750. {
  751. _logger.Info("Validating media library");
  752. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  753. // Start by just validating the children of the root, but go no further
  754. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false);
  755. foreach (var folder in _userManager.Users.Select(u => u.RootFolder).Distinct())
  756. {
  757. await ValidateCollectionFolders(folder, cancellationToken).ConfigureAwait(false);
  758. }
  759. var innerProgress = new ActionableProgress<double>();
  760. innerProgress.RegisterAction(pct => progress.Report(pct * .8));
  761. // Now validate the entire media library
  762. await RootFolder.ValidateChildren(innerProgress, cancellationToken, recursive: true).ConfigureAwait(false);
  763. innerProgress = new ActionableProgress<double>();
  764. innerProgress.RegisterAction(pct => progress.Report(80 + pct * .2));
  765. await ValidateArtists(cancellationToken, innerProgress);
  766. progress.Report(100);
  767. }
  768. /// <summary>
  769. /// Validates only the collection folders for a User and goes no further
  770. /// </summary>
  771. /// <param name="userRootFolder">The user root folder.</param>
  772. /// <param name="cancellationToken">The cancellation token.</param>
  773. /// <returns>Task.</returns>
  774. private async Task ValidateCollectionFolders(UserRootFolder userRootFolder, CancellationToken cancellationToken)
  775. {
  776. _logger.Info("Validating collection folders within {0}", userRootFolder.Path);
  777. await userRootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  778. cancellationToken.ThrowIfCancellationRequested();
  779. await userRootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false).ConfigureAwait(false);
  780. }
  781. /// <summary>
  782. /// Gets the default view.
  783. /// </summary>
  784. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  785. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  786. {
  787. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  788. }
  789. /// <summary>
  790. /// Gets the view.
  791. /// </summary>
  792. /// <param name="user">The user.</param>
  793. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  794. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  795. {
  796. return GetView(user.RootFolderPath);
  797. }
  798. /// <summary>
  799. /// Gets the view.
  800. /// </summary>
  801. /// <param name="path">The path.</param>
  802. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  803. private IEnumerable<VirtualFolderInfo> GetView(string path)
  804. {
  805. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  806. .Select(dir => new VirtualFolderInfo
  807. {
  808. Name = Path.GetFileName(dir),
  809. Locations = Directory.EnumerateFiles(dir, "*.lnk", SearchOption.TopDirectoryOnly).Select(FileSystem.ResolveShortcut).OrderBy(i => i).ToList()
  810. });
  811. }
  812. /// <summary>
  813. /// Gets the item by id.
  814. /// </summary>
  815. /// <param name="id">The id.</param>
  816. /// <returns>BaseItem.</returns>
  817. /// <exception cref="System.ArgumentNullException">id</exception>
  818. public BaseItem GetItemById(Guid id)
  819. {
  820. if (id == Guid.Empty)
  821. {
  822. throw new ArgumentNullException("id");
  823. }
  824. BaseItem item;
  825. LibraryItemsCache.TryGetValue(id, out item);
  826. return item;
  827. }
  828. /// <summary>
  829. /// Gets the intros.
  830. /// </summary>
  831. /// <param name="item">The item.</param>
  832. /// <param name="user">The user.</param>
  833. /// <returns>IEnumerable{System.String}.</returns>
  834. public IEnumerable<string> GetIntros(BaseItem item, User user)
  835. {
  836. return IntroProviders.SelectMany(i => i.GetIntros(item, user));
  837. }
  838. /// <summary>
  839. /// Sorts the specified sort by.
  840. /// </summary>
  841. /// <param name="items">The items.</param>
  842. /// <param name="user">The user.</param>
  843. /// <param name="sortBy">The sort by.</param>
  844. /// <param name="sortOrder">The sort order.</param>
  845. /// <returns>IEnumerable{BaseItem}.</returns>
  846. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  847. {
  848. var isFirst = true;
  849. IOrderedEnumerable<BaseItem> orderedItems = null;
  850. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  851. {
  852. if (isFirst)
  853. {
  854. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  855. }
  856. else
  857. {
  858. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  859. }
  860. isFirst = false;
  861. }
  862. return orderedItems ?? items;
  863. }
  864. /// <summary>
  865. /// Gets the comparer.
  866. /// </summary>
  867. /// <param name="name">The name.</param>
  868. /// <param name="user">The user.</param>
  869. /// <returns>IBaseItemComparer.</returns>
  870. private IBaseItemComparer GetComparer(string name, User user)
  871. {
  872. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  873. if (comparer != null)
  874. {
  875. // If it requires a user, create a new one, and assign the user
  876. if (comparer is IUserBaseItemComparer)
  877. {
  878. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  879. userComparer.User = user;
  880. userComparer.UserManager = _userManager;
  881. userComparer.UserDataRepository = _userDataRepository;
  882. return userComparer;
  883. }
  884. }
  885. return comparer;
  886. }
  887. /// <summary>
  888. /// Saves the item.
  889. /// </summary>
  890. /// <param name="item">The item.</param>
  891. /// <param name="cancellationToken">The cancellation token.</param>
  892. /// <returns>Task.</returns>
  893. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  894. {
  895. return ItemRepository.SaveItem(item, cancellationToken);
  896. }
  897. /// <summary>
  898. /// Retrieves the item.
  899. /// </summary>
  900. /// <param name="id">The id.</param>
  901. /// <returns>Task{BaseItem}.</returns>
  902. public BaseItem RetrieveItem(Guid id)
  903. {
  904. return ItemRepository.RetrieveItem(id);
  905. }
  906. /// <summary>
  907. /// Saves the children.
  908. /// </summary>
  909. /// <param name="id">The id.</param>
  910. /// <param name="children">The children.</param>
  911. /// <param name="cancellationToken">The cancellation token.</param>
  912. /// <returns>Task.</returns>
  913. public Task SaveChildren(Guid id, IEnumerable<BaseItem> children, CancellationToken cancellationToken)
  914. {
  915. return ItemRepository.SaveChildren(id, children, cancellationToken);
  916. }
  917. /// <summary>
  918. /// Retrieves the children.
  919. /// </summary>
  920. /// <param name="parent">The parent.</param>
  921. /// <returns>IEnumerable{BaseItem}.</returns>
  922. public IEnumerable<BaseItem> RetrieveChildren(Folder parent)
  923. {
  924. return ItemRepository.RetrieveChildren(parent);
  925. }
  926. }
  927. }