LibraryManager.cs 49 KB

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