LibraryManager.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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. // Need to remove subpaths that may have been resolved from shortcuts
  370. // Example: if \\server\movies exists, then strip out \\server\movies\action
  371. if (isPhysicalRoot)
  372. {
  373. var paths = args.FileSystemDictionary.Keys.ToList();
  374. foreach (var subPath in paths.Where(subPath => paths.Any(i => subPath.StartsWith(i.TrimEnd(System.IO.Path.DirectorySeparatorChar) + System.IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))))
  375. {
  376. args.FileSystemDictionary.Remove(subPath);
  377. }
  378. }
  379. }
  380. // Check to see if we should resolve based on our contents
  381. if (args.IsDirectory && !ShouldResolvePathContents(args))
  382. {
  383. return null;
  384. }
  385. return ResolveItem(args);
  386. }
  387. /// <summary>
  388. /// Determines whether a path should be ignored based on its contents - called after the contents have been read
  389. /// </summary>
  390. /// <param name="args">The args.</param>
  391. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  392. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  393. {
  394. // Ignore any folders containing a file called .ignore
  395. return !args.ContainsFileSystemEntryByName(".ignore");
  396. }
  397. /// <summary>
  398. /// Resolves a set of files into a list of BaseItem
  399. /// </summary>
  400. /// <typeparam name="T"></typeparam>
  401. /// <param name="files">The files.</param>
  402. /// <param name="parent">The parent.</param>
  403. /// <returns>List{``0}.</returns>
  404. public List<T> ResolvePaths<T>(IEnumerable<FileSystemInfo> files, Folder parent)
  405. where T : BaseItem
  406. {
  407. var list = new List<T>();
  408. Parallel.ForEach(files, f =>
  409. {
  410. try
  411. {
  412. var item = ResolvePath(f.FullName, parent, f) as T;
  413. if (item != null)
  414. {
  415. lock (list)
  416. {
  417. list.Add(item);
  418. }
  419. }
  420. }
  421. catch (Exception ex)
  422. {
  423. _logger.ErrorException("Error resolving path {0}", ex, f.FullName);
  424. }
  425. });
  426. return list;
  427. }
  428. /// <summary>
  429. /// Creates the root media folder
  430. /// </summary>
  431. /// <returns>AggregateFolder.</returns>
  432. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  433. public AggregateFolder CreateRootFolder()
  434. {
  435. var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
  436. var rootFolder = RetrieveItem(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(rootFolderPath);
  437. // Add in the plug-in folders
  438. foreach (var child in PluginFolderCreators)
  439. {
  440. rootFolder.AddVirtualChild(child.GetFolder());
  441. }
  442. return rootFolder;
  443. }
  444. /// <summary>
  445. /// Gets the user root folder.
  446. /// </summary>
  447. /// <param name="userRootPath">The user root path.</param>
  448. /// <returns>UserRootFolder.</returns>
  449. public UserRootFolder GetUserRootFolder(string userRootPath)
  450. {
  451. return _userRootFolders.GetOrAdd(userRootPath, key => RetrieveItem(userRootPath.GetMBId(typeof(UserRootFolder))) as UserRootFolder ?? (UserRootFolder)ResolvePath(userRootPath));
  452. }
  453. /// <summary>
  454. /// Gets a Person
  455. /// </summary>
  456. /// <param name="name">The name.</param>
  457. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  458. /// <returns>Task{Person}.</returns>
  459. public Task<Person> GetPerson(string name, bool allowSlowProviders = false)
  460. {
  461. return GetPerson(name, CancellationToken.None, allowSlowProviders);
  462. }
  463. /// <summary>
  464. /// Gets a Person
  465. /// </summary>
  466. /// <param name="name">The name.</param>
  467. /// <param name="cancellationToken">The cancellation token.</param>
  468. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  469. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  470. /// <returns>Task{Person}.</returns>
  471. private Task<Person> GetPerson(string name, CancellationToken cancellationToken, bool allowSlowProviders = false, bool forceCreation = false)
  472. {
  473. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name, cancellationToken, allowSlowProviders, forceCreation);
  474. }
  475. /// <summary>
  476. /// Gets a Studio
  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{Studio}.</returns>
  481. public Task<Studio> GetStudio(string name, bool allowSlowProviders = false)
  482. {
  483. return GetItemByName<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, 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<Genre> GetGenre(string name, bool allowSlowProviders = false)
  492. {
  493. return GetItemByName<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name, CancellationToken.None, allowSlowProviders);
  494. }
  495. /// <summary>
  496. /// Gets a Genre
  497. /// </summary>
  498. /// <param name="name">The name.</param>
  499. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  500. /// <returns>Task{Genre}.</returns>
  501. public Task<Artist> GetArtist(string name, bool allowSlowProviders = false)
  502. {
  503. return GetArtist(name, CancellationToken.None, allowSlowProviders);
  504. }
  505. /// <summary>
  506. /// Gets the artist.
  507. /// </summary>
  508. /// <param name="name">The name.</param>
  509. /// <param name="cancellationToken">The cancellation token.</param>
  510. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  511. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  512. /// <returns>Task{Artist}.</returns>
  513. private Task<Artist> GetArtist(string name, CancellationToken cancellationToken, bool allowSlowProviders = false, bool forceCreation = false)
  514. {
  515. return GetItemByName<Artist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name, cancellationToken, allowSlowProviders, forceCreation);
  516. }
  517. /// <summary>
  518. /// The us culture
  519. /// </summary>
  520. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  521. /// <summary>
  522. /// Gets a Year
  523. /// </summary>
  524. /// <param name="value">The value.</param>
  525. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  526. /// <returns>Task{Year}.</returns>
  527. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  528. public Task<Year> GetYear(int value, bool allowSlowProviders = false)
  529. {
  530. if (value <= 0)
  531. {
  532. throw new ArgumentOutOfRangeException();
  533. }
  534. return GetItemByName<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture), CancellationToken.None, allowSlowProviders);
  535. }
  536. /// <summary>
  537. /// The images by name item cache
  538. /// </summary>
  539. private readonly ConcurrentDictionary<string, BaseItem> _itemsByName = new ConcurrentDictionary<string, BaseItem>(StringComparer.OrdinalIgnoreCase);
  540. /// <summary>
  541. /// Generically retrieves an IBN item
  542. /// </summary>
  543. /// <typeparam name="T"></typeparam>
  544. /// <param name="path">The path.</param>
  545. /// <param name="name">The name.</param>
  546. /// <param name="cancellationToken">The cancellation token.</param>
  547. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  548. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  549. /// <returns>Task{``0}.</returns>
  550. /// <exception cref="System.ArgumentNullException">
  551. /// </exception>
  552. private async Task<T> GetItemByName<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true, bool forceCreation = false)
  553. where T : BaseItem, new()
  554. {
  555. if (string.IsNullOrEmpty(path))
  556. {
  557. throw new ArgumentNullException();
  558. }
  559. if (string.IsNullOrEmpty(name))
  560. {
  561. throw new ArgumentNullException();
  562. }
  563. var key = Path.Combine(path, FileSystem.GetValidFilename(name));
  564. BaseItem obj;
  565. if (forceCreation || !_itemsByName.TryGetValue(key, out obj))
  566. {
  567. obj = await CreateItemByName<T>(path, name, cancellationToken, allowSlowProviders).ConfigureAwait(false);
  568. _itemsByName.AddOrUpdate(key, obj, (keyName, oldValue) => obj);
  569. }
  570. return obj as T;
  571. }
  572. /// <summary>
  573. /// Creates an IBN item based on a given path
  574. /// </summary>
  575. /// <typeparam name="T"></typeparam>
  576. /// <param name="path">The path.</param>
  577. /// <param name="name">The name.</param>
  578. /// <param name="cancellationToken">The cancellation token.</param>
  579. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  580. /// <returns>Task{``0}.</returns>
  581. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  582. private async Task<T> CreateItemByName<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  583. where T : BaseItem, new()
  584. {
  585. cancellationToken.ThrowIfCancellationRequested();
  586. path = Path.Combine(path, FileSystem.GetValidFilename(name));
  587. var fileInfo = new DirectoryInfo(path);
  588. var isNew = false;
  589. if (!fileInfo.Exists)
  590. {
  591. Directory.CreateDirectory(path);
  592. fileInfo = new DirectoryInfo(path);
  593. if (!fileInfo.Exists)
  594. {
  595. throw new IOException("Path not created: " + path);
  596. }
  597. isNew = true;
  598. }
  599. cancellationToken.ThrowIfCancellationRequested();
  600. var id = path.GetMBId(typeof(T));
  601. var item = RetrieveItem(id) as T;
  602. if (item == null)
  603. {
  604. item = new T
  605. {
  606. Name = name,
  607. Id = id,
  608. DateCreated = fileInfo.CreationTimeUtc,
  609. DateModified = fileInfo.LastWriteTimeUtc,
  610. Path = path
  611. };
  612. isNew = true;
  613. }
  614. cancellationToken.ThrowIfCancellationRequested();
  615. // Set this now so we don't cause additional file system access during provider executions
  616. item.ResetResolveArgs(fileInfo);
  617. await item.RefreshMetadata(cancellationToken, isNew, allowSlowProviders: allowSlowProviders).ConfigureAwait(false);
  618. cancellationToken.ThrowIfCancellationRequested();
  619. return item;
  620. }
  621. /// <summary>
  622. /// Validate and refresh the People sub-set of the IBN.
  623. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  624. /// </summary>
  625. /// <param name="cancellationToken">The cancellation token.</param>
  626. /// <param name="progress">The progress.</param>
  627. /// <returns>Task.</returns>
  628. public async Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  629. {
  630. const int maxTasks = 25;
  631. var tasks = new List<Task>();
  632. var includedPersonTypes = new[] { PersonType.Actor, PersonType.Director, PersonType.GuestStar, PersonType.Writer, PersonType.Director, PersonType.Producer };
  633. var people = RootFolder.RecursiveChildren
  634. .Where(c => c.People != null)
  635. .SelectMany(c => c.People.Where(p => includedPersonTypes.Contains(p.Type)))
  636. .DistinctBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
  637. .ToList();
  638. var numComplete = 0;
  639. foreach (var person in people)
  640. {
  641. if (tasks.Count > maxTasks)
  642. {
  643. await Task.WhenAll(tasks).ConfigureAwait(false);
  644. tasks.Clear();
  645. // Safe cancellation point, when there are no pending tasks
  646. cancellationToken.ThrowIfCancellationRequested();
  647. }
  648. // Avoid accessing the foreach variable within the closure
  649. var currentPerson = person;
  650. tasks.Add(Task.Run(async () =>
  651. {
  652. cancellationToken.ThrowIfCancellationRequested();
  653. try
  654. {
  655. await GetPerson(currentPerson.Name, cancellationToken, true, true).ConfigureAwait(false);
  656. }
  657. catch (IOException ex)
  658. {
  659. _logger.ErrorException("Error validating IBN entry {0}", ex, currentPerson.Name);
  660. }
  661. // Update progress
  662. lock (progress)
  663. {
  664. numComplete++;
  665. double percent = numComplete;
  666. percent /= people.Count;
  667. progress.Report(100 * percent);
  668. }
  669. }));
  670. }
  671. await Task.WhenAll(tasks).ConfigureAwait(false);
  672. progress.Report(100);
  673. _logger.Info("People validation complete");
  674. }
  675. public async Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  676. {
  677. const int maxTasks = 25;
  678. var tasks = new List<Task>();
  679. var artists = RootFolder.RecursiveChildren
  680. .OfType<Audio>()
  681. .SelectMany(c =>
  682. {
  683. var list = new List<string>();
  684. if (!string.IsNullOrEmpty(c.AlbumArtist))
  685. {
  686. list.Add(c.AlbumArtist);
  687. }
  688. if (!string.IsNullOrEmpty(c.Artist))
  689. {
  690. list.Add(c.Artist);
  691. }
  692. return list;
  693. })
  694. .Distinct(StringComparer.OrdinalIgnoreCase)
  695. .ToList();
  696. var numComplete = 0;
  697. foreach (var artist in artists)
  698. {
  699. if (tasks.Count > maxTasks)
  700. {
  701. await Task.WhenAll(tasks).ConfigureAwait(false);
  702. tasks.Clear();
  703. // Safe cancellation point, when there are no pending tasks
  704. cancellationToken.ThrowIfCancellationRequested();
  705. }
  706. // Avoid accessing the foreach variable within the closure
  707. var currentArtist = artist;
  708. tasks.Add(Task.Run(async () =>
  709. {
  710. cancellationToken.ThrowIfCancellationRequested();
  711. try
  712. {
  713. await GetArtist(currentArtist, cancellationToken, true, true).ConfigureAwait(false);
  714. }
  715. catch (IOException ex)
  716. {
  717. _logger.ErrorException("Error validating Artist {0}", ex, currentArtist);
  718. }
  719. // Update progress
  720. lock (progress)
  721. {
  722. numComplete++;
  723. double percent = numComplete;
  724. percent /= artists.Count;
  725. progress.Report(100 * percent);
  726. }
  727. }));
  728. }
  729. await Task.WhenAll(tasks).ConfigureAwait(false);
  730. progress.Report(100);
  731. _logger.Info("Artist validation complete");
  732. }
  733. /// <summary>
  734. /// Reloads the root media folder
  735. /// </summary>
  736. /// <param name="progress">The progress.</param>
  737. /// <param name="cancellationToken">The cancellation token.</param>
  738. /// <returns>Task.</returns>
  739. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  740. {
  741. // Just run the scheduled task so that the user can see it
  742. return Task.Run(() => _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>());
  743. }
  744. /// <summary>
  745. /// Validates the media library internal.
  746. /// </summary>
  747. /// <param name="progress">The progress.</param>
  748. /// <param name="cancellationToken">The cancellation token.</param>
  749. /// <returns>Task.</returns>
  750. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  751. {
  752. _logger.Info("Validating media library");
  753. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  754. // Start by just validating the children of the root, but go no further
  755. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false);
  756. foreach (var folder in _userManager.Users.Select(u => u.RootFolder).Distinct())
  757. {
  758. await ValidateCollectionFolders(folder, cancellationToken).ConfigureAwait(false);
  759. }
  760. // Run prescan tasks
  761. foreach (var task in PrescanTasks)
  762. {
  763. try
  764. {
  765. await task.Run(new Progress<double>(), cancellationToken);
  766. }
  767. catch (Exception ex)
  768. {
  769. _logger.ErrorException("Error running prescan task", ex);
  770. }
  771. }
  772. var innerProgress = new ActionableProgress<double>();
  773. innerProgress.RegisterAction(pct => progress.Report(pct * .8));
  774. // Now validate the entire media library
  775. await RootFolder.ValidateChildren(innerProgress, cancellationToken, recursive: true).ConfigureAwait(false);
  776. innerProgress = new ActionableProgress<double>();
  777. innerProgress.RegisterAction(pct => progress.Report(80 + pct * .2));
  778. await ValidateArtists(cancellationToken, innerProgress);
  779. progress.Report(100);
  780. }
  781. /// <summary>
  782. /// Validates only the collection folders for a User and goes no further
  783. /// </summary>
  784. /// <param name="userRootFolder">The user root folder.</param>
  785. /// <param name="cancellationToken">The cancellation token.</param>
  786. /// <returns>Task.</returns>
  787. private async Task ValidateCollectionFolders(UserRootFolder userRootFolder, CancellationToken cancellationToken)
  788. {
  789. _logger.Info("Validating collection folders within {0}", userRootFolder.Path);
  790. await userRootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  791. cancellationToken.ThrowIfCancellationRequested();
  792. await userRootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false).ConfigureAwait(false);
  793. }
  794. /// <summary>
  795. /// Gets the default view.
  796. /// </summary>
  797. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  798. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  799. {
  800. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  801. }
  802. /// <summary>
  803. /// Gets the view.
  804. /// </summary>
  805. /// <param name="user">The user.</param>
  806. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  807. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  808. {
  809. return GetView(user.RootFolderPath);
  810. }
  811. /// <summary>
  812. /// Gets the view.
  813. /// </summary>
  814. /// <param name="path">The path.</param>
  815. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  816. private IEnumerable<VirtualFolderInfo> GetView(string path)
  817. {
  818. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  819. .Select(dir => new VirtualFolderInfo
  820. {
  821. Name = Path.GetFileName(dir),
  822. Locations = Directory.EnumerateFiles(dir, "*.lnk", SearchOption.TopDirectoryOnly).Select(FileSystem.ResolveShortcut).OrderBy(i => i).ToList()
  823. });
  824. }
  825. /// <summary>
  826. /// Gets the item by id.
  827. /// </summary>
  828. /// <param name="id">The id.</param>
  829. /// <returns>BaseItem.</returns>
  830. /// <exception cref="System.ArgumentNullException">id</exception>
  831. public BaseItem GetItemById(Guid id)
  832. {
  833. if (id == Guid.Empty)
  834. {
  835. throw new ArgumentNullException("id");
  836. }
  837. BaseItem item;
  838. if (LibraryItemsCache.TryGetValue(id, out item))
  839. {
  840. return item;
  841. }
  842. return ItemRepository.GetItem(id);
  843. }
  844. /// <summary>
  845. /// Gets the intros.
  846. /// </summary>
  847. /// <param name="item">The item.</param>
  848. /// <param name="user">The user.</param>
  849. /// <returns>IEnumerable{System.String}.</returns>
  850. public IEnumerable<string> GetIntros(BaseItem item, User user)
  851. {
  852. return IntroProviders.SelectMany(i => i.GetIntros(item, user));
  853. }
  854. /// <summary>
  855. /// Sorts the specified sort by.
  856. /// </summary>
  857. /// <param name="items">The items.</param>
  858. /// <param name="user">The user.</param>
  859. /// <param name="sortBy">The sort by.</param>
  860. /// <param name="sortOrder">The sort order.</param>
  861. /// <returns>IEnumerable{BaseItem}.</returns>
  862. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  863. {
  864. var isFirst = true;
  865. IOrderedEnumerable<BaseItem> orderedItems = null;
  866. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  867. {
  868. if (isFirst)
  869. {
  870. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  871. }
  872. else
  873. {
  874. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  875. }
  876. isFirst = false;
  877. }
  878. return orderedItems ?? items;
  879. }
  880. /// <summary>
  881. /// Gets the comparer.
  882. /// </summary>
  883. /// <param name="name">The name.</param>
  884. /// <param name="user">The user.</param>
  885. /// <returns>IBaseItemComparer.</returns>
  886. private IBaseItemComparer GetComparer(string name, User user)
  887. {
  888. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  889. if (comparer != null)
  890. {
  891. // If it requires a user, create a new one, and assign the user
  892. if (comparer is IUserBaseItemComparer)
  893. {
  894. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  895. userComparer.User = user;
  896. userComparer.UserManager = _userManager;
  897. userComparer.UserDataRepository = _userDataRepository;
  898. return userComparer;
  899. }
  900. }
  901. return comparer;
  902. }
  903. /// <summary>
  904. /// Creates the item.
  905. /// </summary>
  906. /// <param name="item">The item.</param>
  907. /// <param name="cancellationToken">The cancellation token.</param>
  908. /// <returns>Task.</returns>
  909. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  910. {
  911. return CreateItems(new[] { item }, cancellationToken);
  912. }
  913. /// <summary>
  914. /// Creates the items.
  915. /// </summary>
  916. /// <param name="items">The items.</param>
  917. /// <param name="cancellationToken">The cancellation token.</param>
  918. /// <returns>Task.</returns>
  919. public async Task CreateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  920. {
  921. var list = items.ToList();
  922. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  923. foreach (var item in list)
  924. {
  925. UpdateItemInLibraryCache(item);
  926. }
  927. if (ItemAdded != null)
  928. {
  929. foreach (var item in list)
  930. {
  931. try
  932. {
  933. ItemAdded(this, new ItemChangeEventArgs { Item = item });
  934. }
  935. catch (Exception ex)
  936. {
  937. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  938. }
  939. }
  940. }
  941. }
  942. /// <summary>
  943. /// Updates the items.
  944. /// </summary>
  945. /// <param name="items">The items.</param>
  946. /// <param name="cancellationToken">The cancellation token.</param>
  947. /// <returns>Task.</returns>
  948. private async Task UpdateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  949. {
  950. var list = items.ToList();
  951. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  952. foreach (var item in list)
  953. {
  954. UpdateItemInLibraryCache(item);
  955. }
  956. if (ItemUpdated != null)
  957. {
  958. foreach (var item in list)
  959. {
  960. try
  961. {
  962. ItemUpdated(this, new ItemChangeEventArgs { Item = item });
  963. }
  964. catch (Exception ex)
  965. {
  966. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  967. }
  968. }
  969. }
  970. }
  971. /// <summary>
  972. /// Updates the item.
  973. /// </summary>
  974. /// <param name="item">The item.</param>
  975. /// <param name="cancellationToken">The cancellation token.</param>
  976. /// <returns>Task.</returns>
  977. public Task UpdateItem(BaseItem item, CancellationToken cancellationToken)
  978. {
  979. return UpdateItems(new[] { item }, cancellationToken);
  980. }
  981. /// <summary>
  982. /// Reports the item removed.
  983. /// </summary>
  984. /// <param name="item">The item.</param>
  985. public void ReportItemRemoved(BaseItem item)
  986. {
  987. if (ItemRemoved != null)
  988. {
  989. try
  990. {
  991. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  992. }
  993. catch (Exception ex)
  994. {
  995. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  996. }
  997. }
  998. }
  999. /// <summary>
  1000. /// Retrieves the item.
  1001. /// </summary>
  1002. /// <param name="id">The id.</param>
  1003. /// <returns>Task{BaseItem}.</returns>
  1004. public BaseItem RetrieveItem(Guid id)
  1005. {
  1006. return ItemRepository.GetItem(id);
  1007. }
  1008. /// <summary>
  1009. /// Saves the children.
  1010. /// </summary>
  1011. /// <param name="id">The id.</param>
  1012. /// <param name="children">The children.</param>
  1013. /// <param name="cancellationToken">The cancellation token.</param>
  1014. /// <returns>Task.</returns>
  1015. public Task SaveChildren(Guid id, IEnumerable<BaseItem> children, CancellationToken cancellationToken)
  1016. {
  1017. return ItemRepository.SaveChildren(id, children, cancellationToken);
  1018. }
  1019. /// <summary>
  1020. /// Retrieves the children.
  1021. /// </summary>
  1022. /// <param name="parent">The parent.</param>
  1023. /// <returns>IEnumerable{BaseItem}.</returns>
  1024. public IEnumerable<BaseItem> RetrieveChildren(Folder parent)
  1025. {
  1026. var children = ItemRepository.RetrieveChildren(parent).ToList();
  1027. foreach (var child in children)
  1028. {
  1029. child.Parent = parent;
  1030. }
  1031. return children;
  1032. }
  1033. }
  1034. }