LibraryManager.cs 52 KB

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