LibraryManager.cs 52 KB

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