LibraryManager.cs 52 KB

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