LibraryManager.cs 42 KB

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