LibraryManager.cs 41 KB

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