Folder.cs 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.Progress;
  3. using MediaBrowser.Controller.Entities.TV;
  4. using MediaBrowser.Controller.IO;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Localization;
  7. using MediaBrowser.Controller.Resolvers;
  8. using MediaBrowser.Model.Entities;
  9. using MoreLinq;
  10. using System;
  11. using System.Collections;
  12. using System.Collections.Concurrent;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Runtime.Serialization;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Controller.Entities
  20. {
  21. /// <summary>
  22. /// Class Folder
  23. /// </summary>
  24. public class Folder : BaseItem
  25. {
  26. public static IUserManager UserManager { get; set; }
  27. public Folder()
  28. {
  29. LinkedChildren = new List<LinkedChild>();
  30. }
  31. /// <summary>
  32. /// Gets a value indicating whether this instance is folder.
  33. /// </summary>
  34. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  35. [IgnoreDataMember]
  36. public override bool IsFolder
  37. {
  38. get
  39. {
  40. return true;
  41. }
  42. }
  43. /// <summary>
  44. /// Gets or sets a value indicating whether this instance is physical root.
  45. /// </summary>
  46. /// <value><c>true</c> if this instance is physical root; otherwise, <c>false</c>.</value>
  47. public bool IsPhysicalRoot { get; set; }
  48. /// <summary>
  49. /// Gets or sets a value indicating whether this instance is root.
  50. /// </summary>
  51. /// <value><c>true</c> if this instance is root; otherwise, <c>false</c>.</value>
  52. public bool IsRoot { get; set; }
  53. /// <summary>
  54. /// Gets a value indicating whether this instance is virtual folder.
  55. /// </summary>
  56. /// <value><c>true</c> if this instance is virtual folder; otherwise, <c>false</c>.</value>
  57. [IgnoreDataMember]
  58. public virtual bool IsVirtualFolder
  59. {
  60. get
  61. {
  62. return false;
  63. }
  64. }
  65. public virtual List<LinkedChild> LinkedChildren { get; set; }
  66. protected virtual bool SupportsShortcutChildren
  67. {
  68. get { return true; }
  69. }
  70. /// <summary>
  71. /// Adds the child.
  72. /// </summary>
  73. /// <param name="item">The item.</param>
  74. /// <param name="cancellationToken">The cancellation token.</param>
  75. /// <returns>Task.</returns>
  76. /// <exception cref="System.InvalidOperationException">Unable to add + item.Name</exception>
  77. public async Task AddChild(BaseItem item, CancellationToken cancellationToken)
  78. {
  79. item.Parent = this;
  80. if (item.Id == Guid.Empty)
  81. {
  82. item.Id = item.Path.GetMBId(item.GetType());
  83. }
  84. if (_children.Any(i => i.Id == item.Id))
  85. {
  86. throw new ArgumentException(string.Format("A child with the Id {0} already exists.", item.Id));
  87. }
  88. if (item.DateCreated == DateTime.MinValue)
  89. {
  90. item.DateCreated = DateTime.UtcNow;
  91. }
  92. if (item.DateModified == DateTime.MinValue)
  93. {
  94. item.DateModified = DateTime.UtcNow;
  95. }
  96. AddChildInternal(item);
  97. await LibraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  98. await ItemRepository.SaveChildren(Id, _children.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  99. }
  100. protected void AddChildrenInternal(IEnumerable<BaseItem> children)
  101. {
  102. lock (_childrenSyncLock)
  103. {
  104. var newChildren = _children.ToList();
  105. newChildren.AddRange(children);
  106. _children = newChildren;
  107. }
  108. }
  109. protected void AddChildInternal(BaseItem child)
  110. {
  111. lock (_childrenSyncLock)
  112. {
  113. var newChildren = _children.ToList();
  114. newChildren.Add(child);
  115. _children = newChildren;
  116. }
  117. }
  118. protected void RemoveChildrenInternal(IEnumerable<BaseItem> children)
  119. {
  120. lock (_childrenSyncLock)
  121. {
  122. _children = _children.Except(children).ToList();
  123. }
  124. }
  125. protected void ClearChildrenInternal()
  126. {
  127. lock (_childrenSyncLock)
  128. {
  129. _children = new List<BaseItem>();
  130. }
  131. }
  132. /// <summary>
  133. /// Never want folders to be blocked by "BlockNotRated"
  134. /// </summary>
  135. [IgnoreDataMember]
  136. public override string OfficialRatingForComparison
  137. {
  138. get
  139. {
  140. if (this is Series)
  141. {
  142. return base.OfficialRatingForComparison;
  143. }
  144. return !string.IsNullOrEmpty(base.OfficialRatingForComparison) ? base.OfficialRatingForComparison : "None";
  145. }
  146. }
  147. /// <summary>
  148. /// Removes the child.
  149. /// </summary>
  150. /// <param name="item">The item.</param>
  151. /// <param name="cancellationToken">The cancellation token.</param>
  152. /// <returns>Task.</returns>
  153. /// <exception cref="System.InvalidOperationException">Unable to remove + item.Name</exception>
  154. public Task RemoveChild(BaseItem item, CancellationToken cancellationToken)
  155. {
  156. RemoveChildrenInternal(new[] { item });
  157. item.Parent = null;
  158. LibraryManager.ReportItemRemoved(item);
  159. return ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken);
  160. }
  161. /// <summary>
  162. /// Clears the children.
  163. /// </summary>
  164. /// <param name="cancellationToken">The cancellation token.</param>
  165. /// <returns>Task.</returns>
  166. public Task ClearChildren(CancellationToken cancellationToken)
  167. {
  168. var items = ActualChildren.ToList();
  169. ClearChildrenInternal();
  170. foreach (var item in items)
  171. {
  172. LibraryManager.ReportItemRemoved(item);
  173. }
  174. return ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken);
  175. }
  176. #region Indexing
  177. /// <summary>
  178. /// The _index by options
  179. /// </summary>
  180. private Dictionary<string, Func<User, IEnumerable<BaseItem>>> _indexByOptions;
  181. /// <summary>
  182. /// Dictionary of index options - consists of a display value and an indexing function
  183. /// which takes User as a parameter and returns an IEnum of BaseItem
  184. /// </summary>
  185. /// <value>The index by options.</value>
  186. [IgnoreDataMember]
  187. public Dictionary<string, Func<User, IEnumerable<BaseItem>>> IndexByOptions
  188. {
  189. get { return _indexByOptions ?? (_indexByOptions = GetIndexByOptions()); }
  190. }
  191. /// <summary>
  192. /// Returns the valid set of index by options for this folder type.
  193. /// Override or extend to modify.
  194. /// </summary>
  195. /// <returns>Dictionary{System.StringFunc{UserIEnumerable{BaseItem}}}.</returns>
  196. protected virtual Dictionary<string, Func<User, IEnumerable<BaseItem>>> GetIndexByOptions()
  197. {
  198. return new Dictionary<string, Func<User, IEnumerable<BaseItem>>> {
  199. {LocalizedStrings.Instance.GetString("NoneDispPref"), null},
  200. {LocalizedStrings.Instance.GetString("PerformerDispPref"), GetIndexByPerformer},
  201. {LocalizedStrings.Instance.GetString("GenreDispPref"), GetIndexByGenre},
  202. {LocalizedStrings.Instance.GetString("DirectorDispPref"), GetIndexByDirector},
  203. {LocalizedStrings.Instance.GetString("YearDispPref"), GetIndexByYear},
  204. //{LocalizedStrings.Instance.GetString("OfficialRatingDispPref"), null},
  205. {LocalizedStrings.Instance.GetString("StudioDispPref"), GetIndexByStudio}
  206. };
  207. }
  208. /// <summary>
  209. /// Gets the index by actor.
  210. /// </summary>
  211. /// <param name="user">The user.</param>
  212. /// <returns>IEnumerable{BaseItem}.</returns>
  213. protected IEnumerable<BaseItem> GetIndexByPerformer(User user)
  214. {
  215. return GetIndexByPerson(user, new List<string> { PersonType.Actor, PersonType.GuestStar }, true, LocalizedStrings.Instance.GetString("PerformerDispPref"));
  216. }
  217. /// <summary>
  218. /// Gets the index by director.
  219. /// </summary>
  220. /// <param name="user">The user.</param>
  221. /// <returns>IEnumerable{BaseItem}.</returns>
  222. protected IEnumerable<BaseItem> GetIndexByDirector(User user)
  223. {
  224. return GetIndexByPerson(user, new List<string> { PersonType.Director }, false, LocalizedStrings.Instance.GetString("DirectorDispPref"));
  225. }
  226. /// <summary>
  227. /// Gets the index by person.
  228. /// </summary>
  229. /// <param name="user">The user.</param>
  230. /// <param name="personTypes">The person types we should match on</param>
  231. /// <param name="includeAudio">if set to <c>true</c> [include audio].</param>
  232. /// <param name="indexName">Name of the index.</param>
  233. /// <returns>IEnumerable{BaseItem}.</returns>
  234. private IEnumerable<BaseItem> GetIndexByPerson(User user, List<string> personTypes, bool includeAudio, string indexName)
  235. {
  236. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  237. // the retrieval of the individual children for each index value until they are requested.
  238. using (new Profiler(indexName + " Index Build for " + Name, Logger))
  239. {
  240. // Put this in a local variable to avoid an implicitly captured closure
  241. var currentIndexName = indexName;
  242. var us = this;
  243. var recursiveChildren = GetRecursiveChildren(user).Where(i => i.IncludeInIndex).ToList();
  244. // Get the candidates, but handle audio separately
  245. var candidates = recursiveChildren.Where(i => i.AllPeople != null && !(i is Audio.Audio)).ToList();
  246. var indexFolders = candidates.AsParallel().SelectMany(i => i.AllPeople.Where(p => personTypes.Contains(p.Type))
  247. .Select(a => a.Name))
  248. .Distinct()
  249. .Select(i =>
  250. {
  251. try
  252. {
  253. return LibraryManager.GetPerson(i);
  254. }
  255. catch (IOException ex)
  256. {
  257. Logger.ErrorException("Error getting person {0}", ex, i);
  258. return null;
  259. }
  260. catch (AggregateException ex)
  261. {
  262. Logger.ErrorException("Error getting person {0}", ex, i);
  263. return null;
  264. }
  265. })
  266. .Where(i => i != null)
  267. .Select(a => new IndexFolder(us, a,
  268. candidates.Where(i => i.AllPeople.Any(p => personTypes.Contains(p.Type) && p.Name.Equals(a.Name, StringComparison.OrdinalIgnoreCase))
  269. ), currentIndexName)).AsEnumerable();
  270. if (includeAudio)
  271. {
  272. var songs = recursiveChildren.OfType<Audio.Audio>().ToList();
  273. indexFolders = songs.SelectMany(i => i.Artists)
  274. .Distinct(StringComparer.OrdinalIgnoreCase)
  275. .Select(i =>
  276. {
  277. try
  278. {
  279. return LibraryManager.GetArtist(i);
  280. }
  281. catch (IOException ex)
  282. {
  283. Logger.ErrorException("Error getting artist {0}", ex, i);
  284. return null;
  285. }
  286. catch (AggregateException ex)
  287. {
  288. Logger.ErrorException("Error getting artist {0}", ex, i);
  289. return null;
  290. }
  291. })
  292. .Where(i => i != null)
  293. .Select(a => new IndexFolder(us, a,
  294. songs.Where(i => i.Artists.Contains(a.Name, StringComparer.OrdinalIgnoreCase)
  295. ), currentIndexName)).Concat(indexFolders);
  296. }
  297. return indexFolders;
  298. }
  299. }
  300. /// <summary>
  301. /// Gets the index by studio.
  302. /// </summary>
  303. /// <param name="user">The user.</param>
  304. /// <returns>IEnumerable{BaseItem}.</returns>
  305. protected IEnumerable<BaseItem> GetIndexByStudio(User user)
  306. {
  307. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  308. // the retrieval of the individual children for each index value until they are requested.
  309. using (new Profiler("Studio Index Build for " + Name, Logger))
  310. {
  311. var indexName = LocalizedStrings.Instance.GetString("StudioDispPref");
  312. var candidates = GetRecursiveChildren(user).Where(i => i.IncludeInIndex).ToList();
  313. return candidates.AsParallel().SelectMany(i => i.AllStudios)
  314. .Distinct()
  315. .Select(i =>
  316. {
  317. try
  318. {
  319. return LibraryManager.GetStudio(i);
  320. }
  321. catch (IOException ex)
  322. {
  323. Logger.ErrorException("Error getting studio {0}", ex, i);
  324. return null;
  325. }
  326. catch (AggregateException ex)
  327. {
  328. Logger.ErrorException("Error getting studio {0}", ex, i);
  329. return null;
  330. }
  331. })
  332. .Where(i => i != null)
  333. .Select(ndx => new IndexFolder(this, ndx, candidates.Where(i => i.AllStudios.Any(s => s.Equals(ndx.Name, StringComparison.OrdinalIgnoreCase))), indexName));
  334. }
  335. }
  336. /// <summary>
  337. /// Gets the index by genre.
  338. /// </summary>
  339. /// <param name="user">The user.</param>
  340. /// <returns>IEnumerable{BaseItem}.</returns>
  341. protected IEnumerable<BaseItem> GetIndexByGenre(User user)
  342. {
  343. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  344. // the retrieval of the individual children for each index value until they are requested.
  345. using (new Profiler("Genre Index Build for " + Name, Logger))
  346. {
  347. var indexName = LocalizedStrings.Instance.GetString("GenreDispPref");
  348. //we need a copy of this so we don't double-recurse
  349. var candidates = GetRecursiveChildren(user).Where(i => i.IncludeInIndex).ToList();
  350. return candidates.AsParallel().SelectMany(i => i.AllGenres)
  351. .Distinct(StringComparer.OrdinalIgnoreCase)
  352. .Select(i =>
  353. {
  354. try
  355. {
  356. return LibraryManager.GetGenre(i);
  357. }
  358. catch (Exception ex)
  359. {
  360. Logger.ErrorException("Error getting genre {0}", ex, i);
  361. return null;
  362. }
  363. })
  364. .Where(i => i != null)
  365. .Select(genre => new IndexFolder(this, genre, candidates.Where(i => i.AllGenres.Any(g => g.Equals(genre.Name, StringComparison.OrdinalIgnoreCase))), indexName)
  366. );
  367. }
  368. }
  369. /// <summary>
  370. /// Gets the index by year.
  371. /// </summary>
  372. /// <param name="user">The user.</param>
  373. /// <returns>IEnumerable{BaseItem}.</returns>
  374. protected IEnumerable<BaseItem> GetIndexByYear(User user)
  375. {
  376. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  377. // the retrieval of the individual children for each index value until they are requested.
  378. using (new Profiler("Production Year Index Build for " + Name, Logger))
  379. {
  380. var indexName = LocalizedStrings.Instance.GetString("YearDispPref");
  381. //we need a copy of this so we don't double-recurse
  382. var candidates = GetRecursiveChildren(user).Where(i => i.IncludeInIndex && i.ProductionYear.HasValue).ToList();
  383. return candidates.AsParallel().Select(i => i.ProductionYear.Value)
  384. .Distinct()
  385. .Select(i =>
  386. {
  387. try
  388. {
  389. return LibraryManager.GetYear(i);
  390. }
  391. catch (IOException ex)
  392. {
  393. Logger.ErrorException("Error getting year {0}", ex, i);
  394. return null;
  395. }
  396. catch (AggregateException ex)
  397. {
  398. Logger.ErrorException("Error getting year {0}", ex, i);
  399. return null;
  400. }
  401. })
  402. .Where(i => i != null)
  403. .Select(ndx => new IndexFolder(this, ndx, candidates.Where(i => i.ProductionYear == int.Parse(ndx.Name)), indexName));
  404. }
  405. }
  406. /// <summary>
  407. /// Returns the indexed children for this user from the cache. Caches them if not already there.
  408. /// </summary>
  409. /// <param name="user">The user.</param>
  410. /// <param name="indexBy">The index by.</param>
  411. /// <returns>IEnumerable{BaseItem}.</returns>
  412. private IEnumerable<BaseItem> GetIndexedChildren(User user, string indexBy)
  413. {
  414. List<BaseItem> result = null;
  415. var cacheKey = user.Name + indexBy;
  416. if (IndexCache != null)
  417. {
  418. IndexCache.TryGetValue(cacheKey, out result);
  419. }
  420. if (result == null)
  421. {
  422. //not cached - cache it
  423. Func<User, IEnumerable<BaseItem>> indexing;
  424. IndexByOptions.TryGetValue(indexBy, out indexing);
  425. result = BuildIndex(indexBy, indexing, user);
  426. }
  427. return result;
  428. }
  429. /// <summary>
  430. /// Get the list of indexy by choices for this folder (localized).
  431. /// </summary>
  432. /// <value>The index by option strings.</value>
  433. [IgnoreDataMember]
  434. public IEnumerable<string> IndexByOptionStrings
  435. {
  436. get { return IndexByOptions.Keys; }
  437. }
  438. /// <summary>
  439. /// The index cache
  440. /// </summary>
  441. protected ConcurrentDictionary<string, List<BaseItem>> IndexCache;
  442. /// <summary>
  443. /// Builds the index.
  444. /// </summary>
  445. /// <param name="indexKey">The index key.</param>
  446. /// <param name="indexFunction">The index function.</param>
  447. /// <param name="user">The user.</param>
  448. /// <returns>List{BaseItem}.</returns>
  449. protected virtual List<BaseItem> BuildIndex(string indexKey, Func<User, IEnumerable<BaseItem>> indexFunction, User user)
  450. {
  451. if (IndexCache == null)
  452. {
  453. IndexCache = new ConcurrentDictionary<string, List<BaseItem>>();
  454. }
  455. return indexFunction != null
  456. ? IndexCache[user.Name + indexKey] = indexFunction(user).ToList()
  457. : null;
  458. }
  459. #endregion
  460. /// <summary>
  461. /// The children
  462. /// </summary>
  463. private IReadOnlyList<BaseItem> _children = new List<BaseItem>();
  464. /// <summary>
  465. /// The _children sync lock
  466. /// </summary>
  467. private readonly object _childrenSyncLock = new object();
  468. /// <summary>
  469. /// Gets or sets the actual children.
  470. /// </summary>
  471. /// <value>The actual children.</value>
  472. protected virtual IEnumerable<BaseItem> ActualChildren
  473. {
  474. get
  475. {
  476. return _children;
  477. }
  478. }
  479. public void LoadSavedChildren()
  480. {
  481. _children = LoadChildrenInternal();
  482. }
  483. /// <summary>
  484. /// thread-safe access to the actual children of this folder - without regard to user
  485. /// </summary>
  486. /// <value>The children.</value>
  487. [IgnoreDataMember]
  488. public IEnumerable<BaseItem> Children
  489. {
  490. get { return ActualChildren; }
  491. }
  492. /// <summary>
  493. /// thread-safe access to all recursive children of this folder - without regard to user
  494. /// </summary>
  495. /// <value>The recursive children.</value>
  496. [IgnoreDataMember]
  497. public IEnumerable<BaseItem> RecursiveChildren
  498. {
  499. get { return GetRecursiveChildren(); }
  500. }
  501. private List<BaseItem> LoadChildrenInternal()
  502. {
  503. return LoadChildren().ToList();
  504. }
  505. /// <summary>
  506. /// Loads our children. Validation will occur externally.
  507. /// We want this sychronous.
  508. /// </summary>
  509. protected virtual IEnumerable<BaseItem> LoadChildren()
  510. {
  511. //just load our children from the repo - the library will be validated and maintained in other processes
  512. return GetCachedChildren();
  513. }
  514. /// <summary>
  515. /// Gets or sets the current validation cancellation token source.
  516. /// </summary>
  517. /// <value>The current validation cancellation token source.</value>
  518. private CancellationTokenSource CurrentValidationCancellationTokenSource { get; set; }
  519. /// <summary>
  520. /// Validates that the children of the folder still exist
  521. /// </summary>
  522. /// <param name="progress">The progress.</param>
  523. /// <param name="cancellationToken">The cancellation token.</param>
  524. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  525. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  526. /// <returns>Task.</returns>
  527. public async Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken, bool? recursive = null, bool forceRefreshMetadata = false)
  528. {
  529. cancellationToken.ThrowIfCancellationRequested();
  530. // Cancel the current validation, if any
  531. if (CurrentValidationCancellationTokenSource != null)
  532. {
  533. CurrentValidationCancellationTokenSource.Cancel();
  534. }
  535. // Create an inner cancellation token. This can cancel all validations from this level on down,
  536. // but nothing above this
  537. var innerCancellationTokenSource = new CancellationTokenSource();
  538. try
  539. {
  540. CurrentValidationCancellationTokenSource = innerCancellationTokenSource;
  541. var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(innerCancellationTokenSource.Token, cancellationToken);
  542. await ValidateChildrenInternal(progress, linkedCancellationTokenSource.Token, recursive, forceRefreshMetadata).ConfigureAwait(false);
  543. }
  544. catch (OperationCanceledException ex)
  545. {
  546. Logger.Info("ValidateChildren cancelled for " + Name);
  547. // If the outer cancelletion token in the cause for the cancellation, throw it
  548. if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken)
  549. {
  550. throw;
  551. }
  552. }
  553. finally
  554. {
  555. // Null out the token source
  556. if (CurrentValidationCancellationTokenSource == innerCancellationTokenSource)
  557. {
  558. CurrentValidationCancellationTokenSource = null;
  559. }
  560. innerCancellationTokenSource.Dispose();
  561. }
  562. }
  563. /// <summary>
  564. /// Compare our current children (presumably just read from the repo) with the current state of the file system and adjust for any changes
  565. /// ***Currently does not contain logic to maintain items that are unavailable in the file system***
  566. /// </summary>
  567. /// <param name="progress">The progress.</param>
  568. /// <param name="cancellationToken">The cancellation token.</param>
  569. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  570. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  571. /// <returns>Task.</returns>
  572. protected async virtual Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool? recursive = null, bool forceRefreshMetadata = false)
  573. {
  574. var locationType = LocationType;
  575. // Nothing to do here
  576. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  577. {
  578. return;
  579. }
  580. cancellationToken.ThrowIfCancellationRequested();
  581. IEnumerable<BaseItem> nonCachedChildren;
  582. try
  583. {
  584. nonCachedChildren = GetNonCachedChildren();
  585. }
  586. catch (IOException ex)
  587. {
  588. nonCachedChildren = new BaseItem[] { };
  589. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  590. }
  591. if (nonCachedChildren == null) return; //nothing to validate
  592. progress.Report(5);
  593. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  594. var currentChildren = ActualChildren.ToDictionary(i => i.Id);
  595. //create a list for our validated children
  596. var validChildren = new List<Tuple<BaseItem, bool>>();
  597. var newItems = new List<BaseItem>();
  598. cancellationToken.ThrowIfCancellationRequested();
  599. foreach (var child in nonCachedChildren)
  600. {
  601. BaseItem currentChild;
  602. if (currentChildren.TryGetValue(child.Id, out currentChild))
  603. {
  604. currentChild.ResetResolveArgs(child.ResolveArgs);
  605. //existing item - check if it has changed
  606. if (currentChild.HasChanged(child))
  607. {
  608. EntityResolutionHelper.EnsureDates(currentChild, child.ResolveArgs, false);
  609. validChildren.Add(new Tuple<BaseItem, bool>(currentChild, true));
  610. }
  611. else
  612. {
  613. validChildren.Add(new Tuple<BaseItem, bool>(currentChild, false));
  614. }
  615. currentChild.IsOffline = false;
  616. }
  617. else
  618. {
  619. //brand new item - needs to be added
  620. newItems.Add(child);
  621. validChildren.Add(new Tuple<BaseItem, bool>(child, true));
  622. }
  623. }
  624. // If any items were added or removed....
  625. if (newItems.Count > 0 || currentChildren.Count != validChildren.Count)
  626. {
  627. var newChildren = validChildren.Select(c => c.Item1).ToList();
  628. //that's all the new and changed ones - now see if there are any that are missing
  629. var itemsRemoved = currentChildren.Values.Except(newChildren).ToList();
  630. var actualRemovals = new List<BaseItem>();
  631. foreach (var item in itemsRemoved)
  632. {
  633. if (!string.IsNullOrEmpty(item.Path) && IsPathOffline(item.Path))
  634. {
  635. item.IsOffline = true;
  636. validChildren.Add(new Tuple<BaseItem, bool>(item, false));
  637. }
  638. else
  639. {
  640. item.IsOffline = false;
  641. actualRemovals.Add(item);
  642. }
  643. }
  644. if (actualRemovals.Count > 0)
  645. {
  646. RemoveChildrenInternal(actualRemovals);
  647. foreach (var item in actualRemovals)
  648. {
  649. LibraryManager.ReportItemRemoved(item);
  650. }
  651. }
  652. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  653. AddChildrenInternal(newItems);
  654. await ItemRepository.SaveChildren(Id, _children.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  655. //force the indexes to rebuild next time
  656. if (IndexCache != null)
  657. {
  658. IndexCache.Clear();
  659. }
  660. }
  661. progress.Report(10);
  662. cancellationToken.ThrowIfCancellationRequested();
  663. await RefreshChildren(validChildren, progress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  664. progress.Report(100);
  665. }
  666. /// <summary>
  667. /// Refreshes the children.
  668. /// </summary>
  669. /// <param name="children">The children.</param>
  670. /// <param name="progress">The progress.</param>
  671. /// <param name="cancellationToken">The cancellation token.</param>
  672. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  673. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  674. /// <returns>Task.</returns>
  675. private async Task RefreshChildren(IList<Tuple<BaseItem, bool>> children, IProgress<double> progress, CancellationToken cancellationToken, bool? recursive, bool forceRefreshMetadata = false)
  676. {
  677. var list = children;
  678. var percentages = new Dictionary<Guid, double>(list.Count);
  679. var tasks = new List<Task>();
  680. foreach (var tuple in list)
  681. {
  682. if (tasks.Count > 5)
  683. {
  684. await Task.WhenAll(tasks).ConfigureAwait(false);
  685. }
  686. Tuple<BaseItem, bool> currentTuple = tuple;
  687. tasks.Add(Task.Run(async () =>
  688. {
  689. cancellationToken.ThrowIfCancellationRequested();
  690. var child = currentTuple.Item1;
  691. //refresh it
  692. await child.RefreshMetadata(cancellationToken, forceSave: currentTuple.Item2, forceRefresh: forceRefreshMetadata, resetResolveArgs: false).ConfigureAwait(false);
  693. // Refresh children if a folder and the item changed or recursive is set to true
  694. var refreshChildren = child.IsFolder && (currentTuple.Item2 || (recursive.HasValue && recursive.Value));
  695. if (refreshChildren)
  696. {
  697. // Don't refresh children if explicitly set to false
  698. if (recursive.HasValue && recursive.Value == false)
  699. {
  700. refreshChildren = false;
  701. }
  702. }
  703. if (refreshChildren)
  704. {
  705. cancellationToken.ThrowIfCancellationRequested();
  706. var innerProgress = new ActionableProgress<double>();
  707. innerProgress.RegisterAction(p =>
  708. {
  709. lock (percentages)
  710. {
  711. percentages[child.Id] = p / 100;
  712. var percent = percentages.Values.Sum();
  713. percent /= list.Count;
  714. progress.Report((90 * percent) + 10);
  715. }
  716. });
  717. await ((Folder)child).ValidateChildren(innerProgress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  718. // Some folder providers are unable to refresh until children have been refreshed.
  719. await child.RefreshMetadata(cancellationToken, resetResolveArgs: false).ConfigureAwait(false);
  720. }
  721. else
  722. {
  723. lock (percentages)
  724. {
  725. percentages[child.Id] = 1;
  726. var percent = percentages.Values.Sum();
  727. percent /= list.Count;
  728. progress.Report((90 * percent) + 10);
  729. }
  730. }
  731. }));
  732. }
  733. cancellationToken.ThrowIfCancellationRequested();
  734. await Task.WhenAll(tasks).ConfigureAwait(false);
  735. }
  736. /// <summary>
  737. /// Determines whether the specified path is offline.
  738. /// </summary>
  739. /// <param name="path">The path.</param>
  740. /// <returns><c>true</c> if the specified path is offline; otherwise, <c>false</c>.</returns>
  741. private bool IsPathOffline(string path)
  742. {
  743. if (File.Exists(path))
  744. {
  745. return false;
  746. }
  747. var originalPath = path;
  748. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  749. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  750. {
  751. if (Directory.Exists(path))
  752. {
  753. return false;
  754. }
  755. path = System.IO.Path.GetDirectoryName(path);
  756. }
  757. if (ContainsPath(LibraryManager.GetDefaultVirtualFolders(), originalPath))
  758. {
  759. return true;
  760. }
  761. return UserManager.Users.Any(user => ContainsPath(LibraryManager.GetVirtualFolders(user), originalPath));
  762. }
  763. /// <summary>
  764. /// Determines whether the specified folders contains path.
  765. /// </summary>
  766. /// <param name="folders">The folders.</param>
  767. /// <param name="path">The path.</param>
  768. /// <returns><c>true</c> if the specified folders contains path; otherwise, <c>false</c>.</returns>
  769. private bool ContainsPath(IEnumerable<VirtualFolderInfo> folders, string path)
  770. {
  771. return folders.SelectMany(i => i.Locations).Any(i => ContainsPath(i, path));
  772. }
  773. private bool ContainsPath(string parent, string path)
  774. {
  775. return string.Equals(parent, path, StringComparison.OrdinalIgnoreCase) || path.IndexOf(parent.TrimEnd(System.IO.Path.DirectorySeparatorChar) + System.IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) != -1;
  776. }
  777. /// <summary>
  778. /// Get the children of this folder from the actual file system
  779. /// </summary>
  780. /// <returns>IEnumerable{BaseItem}.</returns>
  781. protected virtual IEnumerable<BaseItem> GetNonCachedChildren()
  782. {
  783. if (ResolveArgs == null || ResolveArgs.FileSystemDictionary == null)
  784. {
  785. Logger.Error("Null for {0}", Path);
  786. }
  787. return LibraryManager.ResolvePaths<BaseItem>(ResolveArgs.FileSystemChildren, this);
  788. }
  789. /// <summary>
  790. /// Get our children from the repo - stubbed for now
  791. /// </summary>
  792. /// <returns>IEnumerable{BaseItem}.</returns>
  793. protected IEnumerable<BaseItem> GetCachedChildren()
  794. {
  795. return ItemRepository.GetChildren(Id).Select(RetrieveChild).Where(i => i != null);
  796. }
  797. /// <summary>
  798. /// Retrieves the child.
  799. /// </summary>
  800. /// <param name="child">The child.</param>
  801. /// <returns>BaseItem.</returns>
  802. private BaseItem RetrieveChild(Guid child)
  803. {
  804. var item = LibraryManager.RetrieveItem(child);
  805. if (item != null)
  806. {
  807. if (item is IByReferenceItem)
  808. {
  809. return LibraryManager.GetOrAddByReferenceItem(item);
  810. }
  811. item.Parent = this;
  812. }
  813. return item;
  814. }
  815. /// <summary>
  816. /// Gets allowed children of an item
  817. /// </summary>
  818. /// <param name="user">The user.</param>
  819. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  820. /// <param name="indexBy">The index by.</param>
  821. /// <returns>IEnumerable{BaseItem}.</returns>
  822. /// <exception cref="System.ArgumentNullException"></exception>
  823. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren, string indexBy = null)
  824. {
  825. if (user == null)
  826. {
  827. throw new ArgumentNullException();
  828. }
  829. //the true root should return our users root folder children
  830. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren, indexBy);
  831. IEnumerable<BaseItem> result = null;
  832. if (!string.IsNullOrEmpty(indexBy))
  833. {
  834. result = GetIndexedChildren(user, indexBy);
  835. }
  836. if (result != null)
  837. {
  838. return result;
  839. }
  840. var initialCount = _children.Count;
  841. var list = new List<BaseItem>(initialCount);
  842. AddChildrenToList(user, includeLinkedChildren, list, false, null);
  843. return list;
  844. }
  845. /// <summary>
  846. /// Adds the children to list.
  847. /// </summary>
  848. /// <param name="user">The user.</param>
  849. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  850. /// <param name="list">The list.</param>
  851. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  852. /// <param name="filter">The filter.</param>
  853. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  854. private bool AddChildrenToList(User user, bool includeLinkedChildren, List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  855. {
  856. var hasLinkedChildren = false;
  857. foreach (var child in Children)
  858. {
  859. if (child.IsVisible(user))
  860. {
  861. if (filter == null || filter(child))
  862. {
  863. list.Add(child);
  864. }
  865. }
  866. if (recursive)
  867. {
  868. var folder = child as Folder;
  869. if (folder != null)
  870. {
  871. if (folder.AddChildrenToList(user, includeLinkedChildren, list, true, filter))
  872. {
  873. hasLinkedChildren = true;
  874. }
  875. }
  876. }
  877. }
  878. if (includeLinkedChildren)
  879. {
  880. foreach (var child in GetLinkedChildren())
  881. {
  882. if (filter != null && !filter(child))
  883. {
  884. continue;
  885. }
  886. if (child.IsVisible(user))
  887. {
  888. hasLinkedChildren = true;
  889. list.Add(child);
  890. }
  891. }
  892. }
  893. return hasLinkedChildren;
  894. }
  895. private int _lastRecursiveCount;
  896. /// <summary>
  897. /// Gets allowed recursive children of an item
  898. /// </summary>
  899. /// <param name="user">The user.</param>
  900. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  901. /// <returns>IEnumerable{BaseItem}.</returns>
  902. /// <exception cref="System.ArgumentNullException"></exception>
  903. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  904. {
  905. return GetRecursiveChildren(user, null, includeLinkedChildren);
  906. }
  907. /// <summary>
  908. /// Gets the recursive children.
  909. /// </summary>
  910. /// <param name="user">The user.</param>
  911. /// <param name="filter">The filter.</param>
  912. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  913. /// <returns>IList{BaseItem}.</returns>
  914. /// <exception cref="System.ArgumentNullException"></exception>
  915. public IList<BaseItem> GetRecursiveChildren(User user, Func<BaseItem, bool> filter, bool includeLinkedChildren = true)
  916. {
  917. if (user == null)
  918. {
  919. throw new ArgumentNullException("user");
  920. }
  921. var initialCount = _lastRecursiveCount == 0 ? _children.Count : _lastRecursiveCount;
  922. var list = new List<BaseItem>(initialCount);
  923. var hasLinkedChildren = AddChildrenToList(user, includeLinkedChildren, list, true, filter);
  924. _lastRecursiveCount = list.Count;
  925. return hasLinkedChildren ? list.DistinctBy(i => i.Id).ToList() : list;
  926. }
  927. /// <summary>
  928. /// Gets the recursive children.
  929. /// </summary>
  930. /// <returns>IList{BaseItem}.</returns>
  931. public IList<BaseItem> GetRecursiveChildren()
  932. {
  933. return GetRecursiveChildren(i => true);
  934. }
  935. /// <summary>
  936. /// Gets the recursive children.
  937. /// </summary>
  938. /// <param name="filter">The filter.</param>
  939. /// <returns>IEnumerable{BaseItem}.</returns>
  940. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  941. {
  942. var initialCount = _lastRecursiveCount == 0 ? _children.Count : _lastRecursiveCount;
  943. var list = new List<BaseItem>(initialCount);
  944. AddChildrenToList(list, true, filter);
  945. return list;
  946. }
  947. /// <summary>
  948. /// Adds the children to list.
  949. /// </summary>
  950. /// <param name="list">The list.</param>
  951. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  952. /// <param name="filter">The filter.</param>
  953. private void AddChildrenToList(List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  954. {
  955. foreach (var child in Children)
  956. {
  957. if (filter == null || filter(child))
  958. {
  959. list.Add(child);
  960. }
  961. if (recursive)
  962. {
  963. var folder = child as Folder;
  964. if (folder != null)
  965. {
  966. folder.AddChildrenToList(list, true, filter);
  967. }
  968. }
  969. }
  970. }
  971. /// <summary>
  972. /// Gets the linked children.
  973. /// </summary>
  974. /// <returns>IEnumerable{BaseItem}.</returns>
  975. public IEnumerable<BaseItem> GetLinkedChildren()
  976. {
  977. return LinkedChildren
  978. .Select(GetLinkedChild)
  979. .Where(i => i != null);
  980. }
  981. /// <summary>
  982. /// Gets the linked child.
  983. /// </summary>
  984. /// <param name="info">The info.</param>
  985. /// <returns>BaseItem.</returns>
  986. private BaseItem GetLinkedChild(LinkedChild info)
  987. {
  988. if (string.IsNullOrEmpty(info.Path))
  989. {
  990. throw new ArgumentException("Encountered linked child with empty path.");
  991. }
  992. BaseItem item = null;
  993. // First get using the cached Id
  994. if (info.ItemId != Guid.Empty)
  995. {
  996. item = LibraryManager.GetItemById(info.ItemId);
  997. }
  998. // If still null, search by path
  999. if (item == null)
  1000. {
  1001. item = LibraryManager.RootFolder.FindByPath(info.Path);
  1002. }
  1003. // If still null, log
  1004. if (item == null)
  1005. {
  1006. Logger.Warn("Unable to find linked item at {0}", info.Path);
  1007. }
  1008. else
  1009. {
  1010. // Cache the id for next time
  1011. info.ItemId = item.Id;
  1012. }
  1013. return item;
  1014. }
  1015. public override async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  1016. {
  1017. var changed = await base.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs).ConfigureAwait(false);
  1018. return changed || (SupportsShortcutChildren && LocationType == LocationType.FileSystem && RefreshLinkedChildren());
  1019. }
  1020. /// <summary>
  1021. /// Refreshes the linked children.
  1022. /// </summary>
  1023. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1024. private bool RefreshLinkedChildren()
  1025. {
  1026. ItemResolveArgs resolveArgs;
  1027. try
  1028. {
  1029. resolveArgs = ResolveArgs;
  1030. if (!resolveArgs.IsDirectory)
  1031. {
  1032. return false;
  1033. }
  1034. }
  1035. catch (IOException ex)
  1036. {
  1037. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1038. return false;
  1039. }
  1040. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  1041. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1042. var newShortcutLinks = resolveArgs.FileSystemChildren
  1043. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  1044. .Select(i =>
  1045. {
  1046. try
  1047. {
  1048. Logger.Debug("Found shortcut at {0}", i.FullName);
  1049. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  1050. if (!string.IsNullOrEmpty(resolvedPath))
  1051. {
  1052. return new LinkedChild
  1053. {
  1054. Path = resolvedPath,
  1055. Type = LinkedChildType.Shortcut
  1056. };
  1057. }
  1058. Logger.Error("Error resolving shortcut {0}", i.FullName);
  1059. return null;
  1060. }
  1061. catch (IOException ex)
  1062. {
  1063. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  1064. return null;
  1065. }
  1066. })
  1067. .Where(i => i != null)
  1068. .ToList();
  1069. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  1070. {
  1071. Logger.Info("Shortcut links have changed for {0}", Path);
  1072. newShortcutLinks.AddRange(currentManualLinks);
  1073. LinkedChildren = newShortcutLinks;
  1074. return true;
  1075. }
  1076. return false;
  1077. }
  1078. /// <summary>
  1079. /// Folders need to validate and refresh
  1080. /// </summary>
  1081. /// <returns>Task.</returns>
  1082. public override async Task ChangedExternally()
  1083. {
  1084. await base.ChangedExternally().ConfigureAwait(false);
  1085. var progress = new Progress<double>();
  1086. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  1087. }
  1088. /// <summary>
  1089. /// Marks the played.
  1090. /// </summary>
  1091. /// <param name="user">The user.</param>
  1092. /// <param name="datePlayed">The date played.</param>
  1093. /// <param name="userManager">The user manager.</param>
  1094. /// <returns>Task.</returns>
  1095. public override async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataManager userManager)
  1096. {
  1097. // Sweep through recursively and update status
  1098. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder).Select(c => c.MarkPlayed(user, datePlayed, userManager));
  1099. await Task.WhenAll(tasks).ConfigureAwait(false);
  1100. }
  1101. /// <summary>
  1102. /// Marks the unplayed.
  1103. /// </summary>
  1104. /// <param name="user">The user.</param>
  1105. /// <param name="userManager">The user manager.</param>
  1106. /// <returns>Task.</returns>
  1107. public override async Task MarkUnplayed(User user, IUserDataManager userManager)
  1108. {
  1109. // Sweep through recursively and update status
  1110. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder).Select(c => c.MarkUnplayed(user, userManager));
  1111. await Task.WhenAll(tasks).ConfigureAwait(false);
  1112. }
  1113. /// <summary>
  1114. /// Finds an item by path, recursively
  1115. /// </summary>
  1116. /// <param name="path">The path.</param>
  1117. /// <returns>BaseItem.</returns>
  1118. /// <exception cref="System.ArgumentNullException"></exception>
  1119. public BaseItem FindByPath(string path)
  1120. {
  1121. if (string.IsNullOrEmpty(path))
  1122. {
  1123. throw new ArgumentNullException();
  1124. }
  1125. try
  1126. {
  1127. if (ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1128. {
  1129. return this;
  1130. }
  1131. }
  1132. catch (IOException ex)
  1133. {
  1134. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1135. }
  1136. //this should be functionally equivilent to what was here since it is IEnum and works on a thread-safe copy
  1137. return RecursiveChildren.FirstOrDefault(i =>
  1138. {
  1139. try
  1140. {
  1141. return i.ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase);
  1142. }
  1143. catch (IOException ex)
  1144. {
  1145. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1146. return false;
  1147. }
  1148. });
  1149. }
  1150. }
  1151. }