2
0

LibraryManager.cs 50 KB

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