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