LibraryManager.cs 52 KB

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