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