2
0

LibraryManager.cs 50 KB

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