LibraryManager.cs 52 KB

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