LibraryManager.cs 45 KB

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