LibraryManager.cs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429
  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 = 5;
  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 (Exception ex)
  876. {
  877. _logger.ErrorException("Error running prescan task", ex);
  878. }
  879. }));
  880. await Task.WhenAll(tasks).ConfigureAwait(false);
  881. }
  882. /// <summary>
  883. /// Runs the post scan tasks.
  884. /// </summary>
  885. /// <param name="progress">The progress.</param>
  886. /// <param name="cancellationToken">The cancellation token.</param>
  887. /// <returns>Task.</returns>
  888. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  889. {
  890. var postscanTasks = PostscanTasks.ToList();
  891. var progressDictionary = new Dictionary<ILibraryPostScanTask, double>();
  892. var tasks = postscanTasks.Select(i => Task.Run(async () =>
  893. {
  894. var innerProgress = new ActionableProgress<double>();
  895. innerProgress.RegisterAction(pct =>
  896. {
  897. lock (progressDictionary)
  898. {
  899. progressDictionary[i] = pct;
  900. double percent = progressDictionary.Values.Sum();
  901. percent /= postscanTasks.Count;
  902. progress.Report(75 + percent * .25);
  903. }
  904. });
  905. try
  906. {
  907. await i.Run(innerProgress, cancellationToken);
  908. }
  909. catch (Exception ex)
  910. {
  911. _logger.ErrorException("Error running postscan task", ex);
  912. }
  913. }));
  914. await Task.WhenAll(tasks).ConfigureAwait(false);
  915. }
  916. /// <summary>
  917. /// Validates only the collection folders for a User and goes no further
  918. /// </summary>
  919. /// <param name="userRootFolder">The user root folder.</param>
  920. /// <param name="cancellationToken">The cancellation token.</param>
  921. /// <returns>Task.</returns>
  922. private async Task ValidateCollectionFolders(UserRootFolder userRootFolder, CancellationToken cancellationToken)
  923. {
  924. _logger.Info("Validating collection folders within {0}", userRootFolder.Path);
  925. await userRootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  926. cancellationToken.ThrowIfCancellationRequested();
  927. await userRootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false).ConfigureAwait(false);
  928. }
  929. /// <summary>
  930. /// Gets the default view.
  931. /// </summary>
  932. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  933. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  934. {
  935. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  936. }
  937. /// <summary>
  938. /// Gets the view.
  939. /// </summary>
  940. /// <param name="user">The user.</param>
  941. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  942. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  943. {
  944. return GetView(user.RootFolderPath);
  945. }
  946. /// <summary>
  947. /// Gets the view.
  948. /// </summary>
  949. /// <param name="path">The path.</param>
  950. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  951. private IEnumerable<VirtualFolderInfo> GetView(string path)
  952. {
  953. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  954. .Select(dir => new VirtualFolderInfo
  955. {
  956. Name = Path.GetFileName(dir),
  957. Locations = Directory.EnumerateFiles(dir, "*.lnk", SearchOption.TopDirectoryOnly)
  958. .Select(FileSystem.ResolveShortcut)
  959. .OrderBy(i => i)
  960. .ToList(),
  961. CollectionType = GetCollectionType(dir)
  962. });
  963. }
  964. private string GetCollectionType(string path)
  965. {
  966. return new DirectoryInfo(path).EnumerateFiles("*.collection", SearchOption.TopDirectoryOnly)
  967. .Select(i => Path.GetFileNameWithoutExtension(i.FullName))
  968. .FirstOrDefault();
  969. }
  970. /// <summary>
  971. /// Gets the item by id.
  972. /// </summary>
  973. /// <param name="id">The id.</param>
  974. /// <returns>BaseItem.</returns>
  975. /// <exception cref="System.ArgumentNullException">id</exception>
  976. public BaseItem GetItemById(Guid id)
  977. {
  978. if (id == Guid.Empty)
  979. {
  980. throw new ArgumentNullException("id");
  981. }
  982. BaseItem item;
  983. if (LibraryItemsCache.TryGetValue(id, out item))
  984. {
  985. return item;
  986. }
  987. return RetrieveItem(id);
  988. }
  989. /// <summary>
  990. /// Gets the intros.
  991. /// </summary>
  992. /// <param name="item">The item.</param>
  993. /// <param name="user">The user.</param>
  994. /// <returns>IEnumerable{System.String}.</returns>
  995. public IEnumerable<string> GetIntros(BaseItem item, User user)
  996. {
  997. return IntroProviders.SelectMany(i => i.GetIntros(item, user));
  998. }
  999. /// <summary>
  1000. /// Sorts the specified sort by.
  1001. /// </summary>
  1002. /// <param name="items">The items.</param>
  1003. /// <param name="user">The user.</param>
  1004. /// <param name="sortBy">The sort by.</param>
  1005. /// <param name="sortOrder">The sort order.</param>
  1006. /// <returns>IEnumerable{BaseItem}.</returns>
  1007. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  1008. {
  1009. var isFirst = true;
  1010. IOrderedEnumerable<BaseItem> orderedItems = null;
  1011. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  1012. {
  1013. if (isFirst)
  1014. {
  1015. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  1016. }
  1017. else
  1018. {
  1019. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  1020. }
  1021. isFirst = false;
  1022. }
  1023. return orderedItems ?? items;
  1024. }
  1025. /// <summary>
  1026. /// Gets the comparer.
  1027. /// </summary>
  1028. /// <param name="name">The name.</param>
  1029. /// <param name="user">The user.</param>
  1030. /// <returns>IBaseItemComparer.</returns>
  1031. private IBaseItemComparer GetComparer(string name, User user)
  1032. {
  1033. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  1034. if (comparer != null)
  1035. {
  1036. // If it requires a user, create a new one, and assign the user
  1037. if (comparer is IUserBaseItemComparer)
  1038. {
  1039. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  1040. userComparer.User = user;
  1041. userComparer.UserManager = _userManager;
  1042. userComparer.UserDataRepository = _userDataRepository;
  1043. return userComparer;
  1044. }
  1045. }
  1046. return comparer;
  1047. }
  1048. /// <summary>
  1049. /// Creates the item.
  1050. /// </summary>
  1051. /// <param name="item">The item.</param>
  1052. /// <param name="cancellationToken">The cancellation token.</param>
  1053. /// <returns>Task.</returns>
  1054. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  1055. {
  1056. return CreateItems(new[] { item }, cancellationToken);
  1057. }
  1058. /// <summary>
  1059. /// Creates the items.
  1060. /// </summary>
  1061. /// <param name="items">The items.</param>
  1062. /// <param name="cancellationToken">The cancellation token.</param>
  1063. /// <returns>Task.</returns>
  1064. public async Task CreateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1065. {
  1066. var list = items.ToList();
  1067. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1068. foreach (var item in list)
  1069. {
  1070. UpdateItemInLibraryCache(item);
  1071. }
  1072. if (ItemAdded != null)
  1073. {
  1074. foreach (var item in list)
  1075. {
  1076. try
  1077. {
  1078. ItemAdded(this, new ItemChangeEventArgs { Item = item });
  1079. }
  1080. catch (Exception ex)
  1081. {
  1082. _logger.ErrorException("Error in ItemAdded event handler", ex);
  1083. }
  1084. }
  1085. }
  1086. }
  1087. /// <summary>
  1088. /// Updates the item.
  1089. /// </summary>
  1090. /// <param name="item">The item.</param>
  1091. /// <param name="updateReason">The update reason.</param>
  1092. /// <param name="cancellationToken">The cancellation token.</param>
  1093. /// <returns>Task.</returns>
  1094. public async Task UpdateItem(BaseItem item, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1095. {
  1096. await ItemRepository.SaveItem(item, cancellationToken).ConfigureAwait(false);
  1097. UpdateItemInLibraryCache(item);
  1098. if (item.LocationType == LocationType.FileSystem)
  1099. {
  1100. await SaveMetadata(item, updateReason).ConfigureAwait(false);
  1101. }
  1102. if (ItemUpdated != null)
  1103. {
  1104. try
  1105. {
  1106. ItemUpdated(this, new ItemChangeEventArgs { Item = item });
  1107. }
  1108. catch (Exception ex)
  1109. {
  1110. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  1111. }
  1112. }
  1113. }
  1114. /// <summary>
  1115. /// Reports the item removed.
  1116. /// </summary>
  1117. /// <param name="item">The item.</param>
  1118. public void ReportItemRemoved(BaseItem item)
  1119. {
  1120. if (ItemRemoved != null)
  1121. {
  1122. try
  1123. {
  1124. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1125. }
  1126. catch (Exception ex)
  1127. {
  1128. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1129. }
  1130. }
  1131. }
  1132. /// <summary>
  1133. /// Retrieves the item.
  1134. /// </summary>
  1135. /// <param name="id">The id.</param>
  1136. /// <returns>BaseItem.</returns>
  1137. public BaseItem RetrieveItem(Guid id)
  1138. {
  1139. return ItemRepository.RetrieveItem(id);
  1140. }
  1141. private readonly ConcurrentDictionary<string, SemaphoreSlim> _fileLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  1142. /// <summary>
  1143. /// Saves the metadata.
  1144. /// </summary>
  1145. /// <param name="item">The item.</param>
  1146. /// <param name="updateType">Type of the update.</param>
  1147. /// <returns>Task.</returns>
  1148. private async Task SaveMetadata(BaseItem item, ItemUpdateType updateType)
  1149. {
  1150. foreach (var saver in _savers.Where(i => i.IsEnabledFor(item, updateType)))
  1151. {
  1152. var path = saver.GetSavePath(item);
  1153. var semaphore = _fileLocks.GetOrAdd(path, key => new SemaphoreSlim(1, 1));
  1154. var directoryWatchers = _directoryWatchersFactory();
  1155. await semaphore.WaitAsync().ConfigureAwait(false);
  1156. try
  1157. {
  1158. directoryWatchers.TemporarilyIgnore(path);
  1159. saver.Save(item, CancellationToken.None);
  1160. }
  1161. catch (Exception ex)
  1162. {
  1163. _logger.ErrorException("Error in metadata saver", ex);
  1164. }
  1165. finally
  1166. {
  1167. directoryWatchers.RemoveTempIgnore(path);
  1168. semaphore.Release();
  1169. }
  1170. }
  1171. }
  1172. /// <summary>
  1173. /// Finds the type of the collection.
  1174. /// </summary>
  1175. /// <param name="item">The item.</param>
  1176. /// <returns>System.String.</returns>
  1177. public string FindCollectionType(BaseItem item)
  1178. {
  1179. while (!(item.Parent is AggregateFolder) && item.Parent != null)
  1180. {
  1181. item = item.Parent;
  1182. }
  1183. if (item == null)
  1184. {
  1185. return null;
  1186. }
  1187. var collectionTypes = _userManager.Users
  1188. .Select(i => i.RootFolder)
  1189. .Distinct()
  1190. .SelectMany(i => i.Children)
  1191. .OfType<CollectionFolder>()
  1192. .Where(i =>
  1193. {
  1194. try
  1195. {
  1196. return i.LocationType != LocationType.Remote && i.LocationType != LocationType.Virtual &&
  1197. i.ResolveArgs.PhysicalLocations.Contains(item.Path);
  1198. }
  1199. catch (IOException ex)
  1200. {
  1201. _logger.ErrorException("Error getting resolve args for {0}", ex, i.Path);
  1202. return false;
  1203. }
  1204. })
  1205. .Select(i => i.CollectionType)
  1206. .Where(i => !string.IsNullOrEmpty(i))
  1207. .Distinct()
  1208. .ToList();
  1209. return collectionTypes.Count == 1 ? collectionTypes[0] : null;
  1210. }
  1211. }
  1212. }