LibraryManager.cs 51 KB

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