LibraryManager.cs 42 KB

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