LibraryManager.cs 42 KB

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