2
0

LibraryManager.cs 52 KB

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