LibraryManager.cs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  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. progress.Report(.5);
  755. // Start by just validating the children of the root, but go no further
  756. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false);
  757. progress.Report(1);
  758. foreach (var folder in _userManager.Users.Select(u => u.RootFolder).Distinct())
  759. {
  760. await ValidateCollectionFolders(folder, cancellationToken).ConfigureAwait(false);
  761. }
  762. progress.Report(2);
  763. // Run prescan tasks
  764. await RunPrescanTasks(progress, cancellationToken).ConfigureAwait(false);
  765. progress.Report(15);
  766. var innerProgress = new ActionableProgress<double>();
  767. innerProgress.RegisterAction(pct => progress.Report(15 + pct * .65));
  768. // Now validate the entire media library
  769. await RootFolder.ValidateChildren(innerProgress, cancellationToken, recursive: true).ConfigureAwait(false);
  770. innerProgress = new ActionableProgress<double>();
  771. innerProgress.RegisterAction(pct => progress.Report(80 + pct * .2));
  772. await ValidateArtists(cancellationToken, innerProgress);
  773. progress.Report(100);
  774. }
  775. /// <summary>
  776. /// Runs the prescan tasks.
  777. /// </summary>
  778. /// <param name="progress">The progress.</param>
  779. /// <param name="cancellationToken">The cancellation token.</param>
  780. /// <returns>Task.</returns>
  781. private async Task RunPrescanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  782. {
  783. var prescanTasks = PrescanTasks.ToList();
  784. var progressDictionary = new Dictionary<ILibraryPrescanTask, double>();
  785. var tasks = prescanTasks.Select(i => Task.Run(async () =>
  786. {
  787. var innerProgress = new ActionableProgress<double>();
  788. innerProgress.RegisterAction(pct =>
  789. {
  790. lock (progressDictionary)
  791. {
  792. progressDictionary[i] = pct;
  793. double percent = progressDictionary.Values.Sum();
  794. percent /= prescanTasks.Count;
  795. progress.Report(2 + percent * .13);
  796. }
  797. });
  798. try
  799. {
  800. await i.Run(innerProgress, cancellationToken);
  801. }
  802. catch (Exception ex)
  803. {
  804. _logger.ErrorException("Error running prescan task", ex);
  805. }
  806. }));
  807. // Run prescan tasks
  808. await Task.WhenAll(tasks).ConfigureAwait(false);
  809. }
  810. /// <summary>
  811. /// Validates only the collection folders for a User and goes no further
  812. /// </summary>
  813. /// <param name="userRootFolder">The user root folder.</param>
  814. /// <param name="cancellationToken">The cancellation token.</param>
  815. /// <returns>Task.</returns>
  816. private async Task ValidateCollectionFolders(UserRootFolder userRootFolder, CancellationToken cancellationToken)
  817. {
  818. _logger.Info("Validating collection folders within {0}", userRootFolder.Path);
  819. await userRootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  820. cancellationToken.ThrowIfCancellationRequested();
  821. await userRootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false).ConfigureAwait(false);
  822. }
  823. /// <summary>
  824. /// Gets the default view.
  825. /// </summary>
  826. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  827. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  828. {
  829. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  830. }
  831. /// <summary>
  832. /// Gets the view.
  833. /// </summary>
  834. /// <param name="user">The user.</param>
  835. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  836. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  837. {
  838. return GetView(user.RootFolderPath);
  839. }
  840. /// <summary>
  841. /// Gets the view.
  842. /// </summary>
  843. /// <param name="path">The path.</param>
  844. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  845. private IEnumerable<VirtualFolderInfo> GetView(string path)
  846. {
  847. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  848. .Select(dir => new VirtualFolderInfo
  849. {
  850. Name = Path.GetFileName(dir),
  851. Locations = Directory.EnumerateFiles(dir, "*.lnk", SearchOption.TopDirectoryOnly).Select(FileSystem.ResolveShortcut).OrderBy(i => i).ToList()
  852. });
  853. }
  854. /// <summary>
  855. /// Gets the item by id.
  856. /// </summary>
  857. /// <param name="id">The id.</param>
  858. /// <returns>BaseItem.</returns>
  859. /// <exception cref="System.ArgumentNullException">id</exception>
  860. public BaseItem GetItemById(Guid id)
  861. {
  862. if (id == Guid.Empty)
  863. {
  864. throw new ArgumentNullException("id");
  865. }
  866. BaseItem item;
  867. if (LibraryItemsCache.TryGetValue(id, out item))
  868. {
  869. return item;
  870. }
  871. return ItemRepository.GetItem(id);
  872. }
  873. /// <summary>
  874. /// Gets the intros.
  875. /// </summary>
  876. /// <param name="item">The item.</param>
  877. /// <param name="user">The user.</param>
  878. /// <returns>IEnumerable{System.String}.</returns>
  879. public IEnumerable<string> GetIntros(BaseItem item, User user)
  880. {
  881. return IntroProviders.SelectMany(i => i.GetIntros(item, user));
  882. }
  883. /// <summary>
  884. /// Sorts the specified sort by.
  885. /// </summary>
  886. /// <param name="items">The items.</param>
  887. /// <param name="user">The user.</param>
  888. /// <param name="sortBy">The sort by.</param>
  889. /// <param name="sortOrder">The sort order.</param>
  890. /// <returns>IEnumerable{BaseItem}.</returns>
  891. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  892. {
  893. var isFirst = true;
  894. IOrderedEnumerable<BaseItem> orderedItems = null;
  895. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  896. {
  897. if (isFirst)
  898. {
  899. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  900. }
  901. else
  902. {
  903. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  904. }
  905. isFirst = false;
  906. }
  907. return orderedItems ?? items;
  908. }
  909. /// <summary>
  910. /// Gets the comparer.
  911. /// </summary>
  912. /// <param name="name">The name.</param>
  913. /// <param name="user">The user.</param>
  914. /// <returns>IBaseItemComparer.</returns>
  915. private IBaseItemComparer GetComparer(string name, User user)
  916. {
  917. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  918. if (comparer != null)
  919. {
  920. // If it requires a user, create a new one, and assign the user
  921. if (comparer is IUserBaseItemComparer)
  922. {
  923. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  924. userComparer.User = user;
  925. userComparer.UserManager = _userManager;
  926. userComparer.UserDataRepository = _userDataRepository;
  927. return userComparer;
  928. }
  929. }
  930. return comparer;
  931. }
  932. /// <summary>
  933. /// Creates the item.
  934. /// </summary>
  935. /// <param name="item">The item.</param>
  936. /// <param name="cancellationToken">The cancellation token.</param>
  937. /// <returns>Task.</returns>
  938. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  939. {
  940. return CreateItems(new[] { item }, cancellationToken);
  941. }
  942. /// <summary>
  943. /// Creates the items.
  944. /// </summary>
  945. /// <param name="items">The items.</param>
  946. /// <param name="cancellationToken">The cancellation token.</param>
  947. /// <returns>Task.</returns>
  948. public async Task CreateItems(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 (ItemAdded != null)
  957. {
  958. foreach (var item in list)
  959. {
  960. try
  961. {
  962. ItemAdded(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 items.
  973. /// </summary>
  974. /// <param name="items">The items.</param>
  975. /// <param name="cancellationToken">The cancellation token.</param>
  976. /// <returns>Task.</returns>
  977. private async Task UpdateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  978. {
  979. var list = items.ToList();
  980. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  981. foreach (var item in list)
  982. {
  983. UpdateItemInLibraryCache(item);
  984. }
  985. if (ItemUpdated != null)
  986. {
  987. foreach (var item in list)
  988. {
  989. try
  990. {
  991. ItemUpdated(this, new ItemChangeEventArgs { Item = item });
  992. }
  993. catch (Exception ex)
  994. {
  995. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  996. }
  997. }
  998. }
  999. }
  1000. /// <summary>
  1001. /// Updates the item.
  1002. /// </summary>
  1003. /// <param name="item">The item.</param>
  1004. /// <param name="cancellationToken">The cancellation token.</param>
  1005. /// <returns>Task.</returns>
  1006. public Task UpdateItem(BaseItem item, CancellationToken cancellationToken)
  1007. {
  1008. return UpdateItems(new[] { item }, cancellationToken);
  1009. }
  1010. /// <summary>
  1011. /// Reports the item removed.
  1012. /// </summary>
  1013. /// <param name="item">The item.</param>
  1014. public void ReportItemRemoved(BaseItem item)
  1015. {
  1016. if (ItemRemoved != null)
  1017. {
  1018. try
  1019. {
  1020. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1021. }
  1022. catch (Exception ex)
  1023. {
  1024. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1025. }
  1026. }
  1027. }
  1028. /// <summary>
  1029. /// Retrieves the item.
  1030. /// </summary>
  1031. /// <param name="id">The id.</param>
  1032. /// <returns>Task{BaseItem}.</returns>
  1033. public BaseItem RetrieveItem(Guid id)
  1034. {
  1035. return ItemRepository.GetItem(id);
  1036. }
  1037. /// <summary>
  1038. /// Saves the children.
  1039. /// </summary>
  1040. /// <param name="id">The id.</param>
  1041. /// <param name="children">The children.</param>
  1042. /// <param name="cancellationToken">The cancellation token.</param>
  1043. /// <returns>Task.</returns>
  1044. public Task SaveChildren(Guid id, IEnumerable<BaseItem> children, CancellationToken cancellationToken)
  1045. {
  1046. return ItemRepository.SaveChildren(id, children, cancellationToken);
  1047. }
  1048. /// <summary>
  1049. /// Retrieves the children.
  1050. /// </summary>
  1051. /// <param name="parent">The parent.</param>
  1052. /// <returns>IEnumerable{BaseItem}.</returns>
  1053. public IEnumerable<BaseItem> RetrieveChildren(Folder parent)
  1054. {
  1055. var children = ItemRepository.RetrieveChildren(parent).ToList();
  1056. foreach (var child in children)
  1057. {
  1058. child.Parent = parent;
  1059. }
  1060. return children;
  1061. }
  1062. }
  1063. }