2
0

LibraryManager.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  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 videoBackdrops = items.SelectMany(i => i.ThemeSongs).ToList();
  242. items.AddRange(specialFeatures);
  243. items.AddRange(localTrailers);
  244. items.AddRange(themeSongs);
  245. items.AddRange(videoBackdrops);
  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.VideoBackdrops)
  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. rootFolder.AddVirtualChild(child.GetFolder());
  447. }
  448. return rootFolder;
  449. }
  450. /// <summary>
  451. /// Gets the user root folder.
  452. /// </summary>
  453. /// <param name="userRootPath">The user root path.</param>
  454. /// <returns>UserRootFolder.</returns>
  455. public UserRootFolder GetUserRootFolder(string userRootPath)
  456. {
  457. return _userRootFolders.GetOrAdd(userRootPath, key => RetrieveItem(userRootPath.GetMBId(typeof(UserRootFolder))) as UserRootFolder ?? (UserRootFolder)ResolvePath(userRootPath));
  458. }
  459. /// <summary>
  460. /// Gets a Person
  461. /// </summary>
  462. /// <param name="name">The name.</param>
  463. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  464. /// <returns>Task{Person}.</returns>
  465. public Task<Person> GetPerson(string name, bool allowSlowProviders = false)
  466. {
  467. return GetPerson(name, CancellationToken.None, allowSlowProviders);
  468. }
  469. /// <summary>
  470. /// Gets a Person
  471. /// </summary>
  472. /// <param name="name">The name.</param>
  473. /// <param name="cancellationToken">The cancellation token.</param>
  474. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  475. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  476. /// <returns>Task{Person}.</returns>
  477. private Task<Person> GetPerson(string name, CancellationToken cancellationToken, bool allowSlowProviders = false, bool forceCreation = false)
  478. {
  479. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name, cancellationToken, allowSlowProviders, forceCreation);
  480. }
  481. /// <summary>
  482. /// Gets a Studio
  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{Studio}.</returns>
  487. public Task<Studio> GetStudio(string name, bool allowSlowProviders = false)
  488. {
  489. return GetItemByName<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name, CancellationToken.None, allowSlowProviders);
  490. }
  491. /// <summary>
  492. /// Gets a Genre
  493. /// </summary>
  494. /// <param name="name">The name.</param>
  495. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  496. /// <returns>Task{Genre}.</returns>
  497. public Task<Genre> GetGenre(string name, bool allowSlowProviders = false)
  498. {
  499. return GetItemByName<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name, CancellationToken.None, allowSlowProviders);
  500. }
  501. /// <summary>
  502. /// Gets a Genre
  503. /// </summary>
  504. /// <param name="name">The name.</param>
  505. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  506. /// <returns>Task{Genre}.</returns>
  507. public Task<Artist> GetArtist(string name, bool allowSlowProviders = false)
  508. {
  509. return GetArtist(name, CancellationToken.None, allowSlowProviders);
  510. }
  511. /// <summary>
  512. /// Gets the artist.
  513. /// </summary>
  514. /// <param name="name">The name.</param>
  515. /// <param name="cancellationToken">The cancellation token.</param>
  516. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  517. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  518. /// <returns>Task{Artist}.</returns>
  519. private Task<Artist> GetArtist(string name, CancellationToken cancellationToken, bool allowSlowProviders = false, bool forceCreation = false)
  520. {
  521. return GetItemByName<Artist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name, cancellationToken, allowSlowProviders, forceCreation);
  522. }
  523. /// <summary>
  524. /// The us culture
  525. /// </summary>
  526. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  527. /// <summary>
  528. /// Gets a Year
  529. /// </summary>
  530. /// <param name="value">The value.</param>
  531. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  532. /// <returns>Task{Year}.</returns>
  533. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  534. public Task<Year> GetYear(int value, bool allowSlowProviders = false)
  535. {
  536. if (value <= 0)
  537. {
  538. throw new ArgumentOutOfRangeException();
  539. }
  540. return GetItemByName<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture), CancellationToken.None, allowSlowProviders);
  541. }
  542. /// <summary>
  543. /// The images by name item cache
  544. /// </summary>
  545. private readonly ConcurrentDictionary<string, BaseItem> _itemsByName = new ConcurrentDictionary<string, BaseItem>(StringComparer.OrdinalIgnoreCase);
  546. /// <summary>
  547. /// Generically retrieves an IBN item
  548. /// </summary>
  549. /// <typeparam name="T"></typeparam>
  550. /// <param name="path">The path.</param>
  551. /// <param name="name">The name.</param>
  552. /// <param name="cancellationToken">The cancellation token.</param>
  553. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  554. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  555. /// <returns>Task{``0}.</returns>
  556. /// <exception cref="System.ArgumentNullException">
  557. /// </exception>
  558. private async Task<T> GetItemByName<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true, bool forceCreation = false)
  559. where T : BaseItem, new()
  560. {
  561. if (string.IsNullOrEmpty(path))
  562. {
  563. throw new ArgumentNullException();
  564. }
  565. if (string.IsNullOrEmpty(name))
  566. {
  567. throw new ArgumentNullException();
  568. }
  569. var key = Path.Combine(path, FileSystem.GetValidFilename(name));
  570. BaseItem obj;
  571. if (forceCreation || !_itemsByName.TryGetValue(key, out obj))
  572. {
  573. obj = await CreateItemByName<T>(path, name, cancellationToken, allowSlowProviders).ConfigureAwait(false);
  574. _itemsByName.AddOrUpdate(key, obj, (keyName, oldValue) => obj);
  575. }
  576. return obj as T;
  577. }
  578. /// <summary>
  579. /// Creates an IBN item based on a given path
  580. /// </summary>
  581. /// <typeparam name="T"></typeparam>
  582. /// <param name="path">The path.</param>
  583. /// <param name="name">The name.</param>
  584. /// <param name="cancellationToken">The cancellation token.</param>
  585. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  586. /// <returns>Task{``0}.</returns>
  587. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  588. private async Task<T> CreateItemByName<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  589. where T : BaseItem, new()
  590. {
  591. cancellationToken.ThrowIfCancellationRequested();
  592. _logger.Debug("Getting {0}: {1}", typeof(T).Name, name);
  593. path = Path.Combine(path, FileSystem.GetValidFilename(name));
  594. var fileInfo = new DirectoryInfo(path);
  595. var isNew = false;
  596. if (!fileInfo.Exists)
  597. {
  598. Directory.CreateDirectory(path);
  599. fileInfo = new DirectoryInfo(path);
  600. if (!fileInfo.Exists)
  601. {
  602. throw new IOException("Path not created: " + path);
  603. }
  604. isNew = true;
  605. }
  606. cancellationToken.ThrowIfCancellationRequested();
  607. var id = path.GetMBId(typeof(T));
  608. var item = RetrieveItem(id) as T;
  609. if (item == null)
  610. {
  611. item = new T
  612. {
  613. Name = name,
  614. Id = id,
  615. DateCreated = fileInfo.CreationTimeUtc,
  616. DateModified = fileInfo.LastWriteTimeUtc,
  617. Path = path
  618. };
  619. isNew = true;
  620. }
  621. cancellationToken.ThrowIfCancellationRequested();
  622. // Set this now so we don't cause additional file system access during provider executions
  623. item.ResetResolveArgs(fileInfo);
  624. await item.RefreshMetadata(cancellationToken, isNew, allowSlowProviders: allowSlowProviders).ConfigureAwait(false);
  625. cancellationToken.ThrowIfCancellationRequested();
  626. return item;
  627. }
  628. /// <summary>
  629. /// Validate and refresh the People sub-set of the IBN.
  630. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  631. /// </summary>
  632. /// <param name="cancellationToken">The cancellation token.</param>
  633. /// <param name="progress">The progress.</param>
  634. /// <returns>Task.</returns>
  635. public async Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  636. {
  637. const int maxTasks = 25;
  638. var tasks = new List<Task>();
  639. var includedPersonTypes = new[] { PersonType.Actor, PersonType.Director, PersonType.GuestStar, PersonType.Writer, PersonType.Director, PersonType.Producer };
  640. var people = RootFolder.RecursiveChildren
  641. .Where(c => c.People != null)
  642. .SelectMany(c => c.People.Where(p => includedPersonTypes.Contains(p.Type)))
  643. .DistinctBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
  644. .ToList();
  645. var numComplete = 0;
  646. foreach (var person in people)
  647. {
  648. if (tasks.Count > maxTasks)
  649. {
  650. await Task.WhenAll(tasks).ConfigureAwait(false);
  651. tasks.Clear();
  652. // Safe cancellation point, when there are no pending tasks
  653. cancellationToken.ThrowIfCancellationRequested();
  654. }
  655. // Avoid accessing the foreach variable within the closure
  656. var currentPerson = person;
  657. tasks.Add(Task.Run(async () =>
  658. {
  659. cancellationToken.ThrowIfCancellationRequested();
  660. try
  661. {
  662. await GetPerson(currentPerson.Name, cancellationToken, true, true).ConfigureAwait(false);
  663. }
  664. catch (IOException ex)
  665. {
  666. _logger.ErrorException("Error validating IBN entry {0}", ex, currentPerson.Name);
  667. }
  668. // Update progress
  669. lock (progress)
  670. {
  671. numComplete++;
  672. double percent = numComplete;
  673. percent /= people.Count;
  674. progress.Report(100 * percent);
  675. }
  676. }));
  677. }
  678. await Task.WhenAll(tasks).ConfigureAwait(false);
  679. progress.Report(100);
  680. _logger.Info("People validation complete");
  681. }
  682. public async Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  683. {
  684. const int maxTasks = 25;
  685. var tasks = new List<Task>();
  686. var artists = RootFolder.RecursiveChildren
  687. .OfType<Audio>()
  688. .SelectMany(c =>
  689. {
  690. var list = new List<string>();
  691. if (!string.IsNullOrEmpty(c.AlbumArtist))
  692. {
  693. list.Add(c.AlbumArtist);
  694. }
  695. if (!string.IsNullOrEmpty(c.Artist))
  696. {
  697. list.Add(c.Artist);
  698. }
  699. return list;
  700. })
  701. .Distinct(StringComparer.OrdinalIgnoreCase)
  702. .ToList();
  703. var numComplete = 0;
  704. foreach (var artist in artists)
  705. {
  706. if (tasks.Count > maxTasks)
  707. {
  708. await Task.WhenAll(tasks).ConfigureAwait(false);
  709. tasks.Clear();
  710. // Safe cancellation point, when there are no pending tasks
  711. cancellationToken.ThrowIfCancellationRequested();
  712. }
  713. // Avoid accessing the foreach variable within the closure
  714. var currentArtist = artist;
  715. tasks.Add(Task.Run(async () =>
  716. {
  717. cancellationToken.ThrowIfCancellationRequested();
  718. try
  719. {
  720. await GetArtist(currentArtist, cancellationToken, true, true).ConfigureAwait(false);
  721. }
  722. catch (IOException ex)
  723. {
  724. _logger.ErrorException("Error validating Artist {0}", ex, currentArtist);
  725. }
  726. // Update progress
  727. lock (progress)
  728. {
  729. numComplete++;
  730. double percent = numComplete;
  731. percent /= artists.Count;
  732. progress.Report(100 * percent);
  733. }
  734. }));
  735. }
  736. await Task.WhenAll(tasks).ConfigureAwait(false);
  737. progress.Report(100);
  738. _logger.Info("Artist validation complete");
  739. }
  740. /// <summary>
  741. /// Reloads the root media folder
  742. /// </summary>
  743. /// <param name="progress">The progress.</param>
  744. /// <param name="cancellationToken">The cancellation token.</param>
  745. /// <returns>Task.</returns>
  746. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  747. {
  748. // Just run the scheduled task so that the user can see it
  749. return Task.Run(() => _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>());
  750. }
  751. /// <summary>
  752. /// Validates the media library internal.
  753. /// </summary>
  754. /// <param name="progress">The progress.</param>
  755. /// <param name="cancellationToken">The cancellation token.</param>
  756. /// <returns>Task.</returns>
  757. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  758. {
  759. _logger.Info("Validating media library");
  760. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  761. // Start by just validating the children of the root, but go no further
  762. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false);
  763. foreach (var folder in _userManager.Users.Select(u => u.RootFolder).Distinct())
  764. {
  765. await ValidateCollectionFolders(folder, cancellationToken).ConfigureAwait(false);
  766. }
  767. var innerProgress = new ActionableProgress<double>();
  768. innerProgress.RegisterAction(pct => progress.Report(pct * .8));
  769. // Now validate the entire media library
  770. await RootFolder.ValidateChildren(innerProgress, cancellationToken, recursive: true).ConfigureAwait(false);
  771. innerProgress = new ActionableProgress<double>();
  772. innerProgress.RegisterAction(pct => progress.Report(80 + pct * .2));
  773. await ValidateArtists(cancellationToken, innerProgress);
  774. progress.Report(100);
  775. }
  776. /// <summary>
  777. /// Validates only the collection folders for a User and goes no further
  778. /// </summary>
  779. /// <param name="userRootFolder">The user root folder.</param>
  780. /// <param name="cancellationToken">The cancellation token.</param>
  781. /// <returns>Task.</returns>
  782. private async Task ValidateCollectionFolders(UserRootFolder userRootFolder, CancellationToken cancellationToken)
  783. {
  784. _logger.Info("Validating collection folders within {0}", userRootFolder.Path);
  785. await userRootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  786. cancellationToken.ThrowIfCancellationRequested();
  787. await userRootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false).ConfigureAwait(false);
  788. }
  789. /// <summary>
  790. /// Gets the default view.
  791. /// </summary>
  792. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  793. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  794. {
  795. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  796. }
  797. /// <summary>
  798. /// Gets the view.
  799. /// </summary>
  800. /// <param name="user">The user.</param>
  801. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  802. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  803. {
  804. return GetView(user.RootFolderPath);
  805. }
  806. /// <summary>
  807. /// Gets the view.
  808. /// </summary>
  809. /// <param name="path">The path.</param>
  810. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  811. private IEnumerable<VirtualFolderInfo> GetView(string path)
  812. {
  813. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  814. .Select(dir => new VirtualFolderInfo
  815. {
  816. Name = Path.GetFileName(dir),
  817. Locations = Directory.EnumerateFiles(dir, "*.lnk", SearchOption.TopDirectoryOnly).Select(FileSystem.ResolveShortcut).OrderBy(i => i).ToList()
  818. });
  819. }
  820. /// <summary>
  821. /// Gets the item by id.
  822. /// </summary>
  823. /// <param name="id">The id.</param>
  824. /// <returns>BaseItem.</returns>
  825. /// <exception cref="System.ArgumentNullException">id</exception>
  826. public BaseItem GetItemById(Guid id)
  827. {
  828. if (id == Guid.Empty)
  829. {
  830. throw new ArgumentNullException("id");
  831. }
  832. BaseItem item;
  833. LibraryItemsCache.TryGetValue(id, out item);
  834. return item;
  835. }
  836. /// <summary>
  837. /// Gets the intros.
  838. /// </summary>
  839. /// <param name="item">The item.</param>
  840. /// <param name="user">The user.</param>
  841. /// <returns>IEnumerable{System.String}.</returns>
  842. public IEnumerable<string> GetIntros(BaseItem item, User user)
  843. {
  844. return IntroProviders.SelectMany(i => i.GetIntros(item, user));
  845. }
  846. /// <summary>
  847. /// Sorts the specified sort by.
  848. /// </summary>
  849. /// <param name="items">The items.</param>
  850. /// <param name="user">The user.</param>
  851. /// <param name="sortBy">The sort by.</param>
  852. /// <param name="sortOrder">The sort order.</param>
  853. /// <returns>IEnumerable{BaseItem}.</returns>
  854. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  855. {
  856. var isFirst = true;
  857. IOrderedEnumerable<BaseItem> orderedItems = null;
  858. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  859. {
  860. if (isFirst)
  861. {
  862. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  863. }
  864. else
  865. {
  866. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  867. }
  868. isFirst = false;
  869. }
  870. return orderedItems ?? items;
  871. }
  872. /// <summary>
  873. /// Gets the comparer.
  874. /// </summary>
  875. /// <param name="name">The name.</param>
  876. /// <param name="user">The user.</param>
  877. /// <returns>IBaseItemComparer.</returns>
  878. private IBaseItemComparer GetComparer(string name, User user)
  879. {
  880. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  881. if (comparer != null)
  882. {
  883. // If it requires a user, create a new one, and assign the user
  884. if (comparer is IUserBaseItemComparer)
  885. {
  886. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  887. userComparer.User = user;
  888. userComparer.UserManager = _userManager;
  889. userComparer.UserDataRepository = _userDataRepository;
  890. return userComparer;
  891. }
  892. }
  893. return comparer;
  894. }
  895. /// <summary>
  896. /// Saves the item.
  897. /// </summary>
  898. /// <param name="item">The item.</param>
  899. /// <param name="cancellationToken">The cancellation token.</param>
  900. /// <returns>Task.</returns>
  901. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  902. {
  903. return ItemRepository.SaveItem(item, cancellationToken);
  904. }
  905. /// <summary>
  906. /// Retrieves the item.
  907. /// </summary>
  908. /// <param name="id">The id.</param>
  909. /// <returns>Task{BaseItem}.</returns>
  910. public BaseItem RetrieveItem(Guid id)
  911. {
  912. return ItemRepository.RetrieveItem(id);
  913. }
  914. /// <summary>
  915. /// Saves the children.
  916. /// </summary>
  917. /// <param name="id">The id.</param>
  918. /// <param name="children">The children.</param>
  919. /// <param name="cancellationToken">The cancellation token.</param>
  920. /// <returns>Task.</returns>
  921. public Task SaveChildren(Guid id, IEnumerable<BaseItem> children, CancellationToken cancellationToken)
  922. {
  923. return ItemRepository.SaveChildren(id, children, cancellationToken);
  924. }
  925. /// <summary>
  926. /// Retrieves the children.
  927. /// </summary>
  928. /// <param name="parent">The parent.</param>
  929. /// <returns>IEnumerable{BaseItem}.</returns>
  930. public IEnumerable<BaseItem> RetrieveChildren(Folder parent)
  931. {
  932. return ItemRepository.RetrieveChildren(parent);
  933. }
  934. }
  935. }