LibraryManager.cs 43 KB

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