LibraryManager.cs 47 KB

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