LibraryManager.cs 51 KB

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