LibraryManager.cs 51 KB

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