LibraryManager.cs 52 KB

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