Folder.cs 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  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 (item.LocationType == LocationType.Virtual ||
  634. item.LocationType == LocationType.Remote)
  635. {
  636. // Don't remove these because there's no way to accurately validate them.
  637. continue;
  638. }
  639. if (!string.IsNullOrEmpty(item.Path) && IsPathOffline(item.Path))
  640. {
  641. item.IsOffline = true;
  642. validChildren.Add(new Tuple<BaseItem, bool>(item, false));
  643. }
  644. else
  645. {
  646. item.IsOffline = false;
  647. actualRemovals.Add(item);
  648. }
  649. }
  650. if (actualRemovals.Count > 0)
  651. {
  652. RemoveChildrenInternal(actualRemovals);
  653. foreach (var item in actualRemovals)
  654. {
  655. LibraryManager.ReportItemRemoved(item);
  656. }
  657. }
  658. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  659. AddChildrenInternal(newItems);
  660. await ItemRepository.SaveChildren(Id, _children.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  661. //force the indexes to rebuild next time
  662. if (IndexCache != null)
  663. {
  664. IndexCache.Clear();
  665. }
  666. }
  667. progress.Report(10);
  668. cancellationToken.ThrowIfCancellationRequested();
  669. await RefreshChildren(validChildren, progress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  670. progress.Report(100);
  671. }
  672. /// <summary>
  673. /// Refreshes the children.
  674. /// </summary>
  675. /// <param name="children">The children.</param>
  676. /// <param name="progress">The progress.</param>
  677. /// <param name="cancellationToken">The cancellation token.</param>
  678. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  679. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  680. /// <returns>Task.</returns>
  681. private async Task RefreshChildren(IList<Tuple<BaseItem, bool>> children, IProgress<double> progress, CancellationToken cancellationToken, bool? recursive, bool forceRefreshMetadata = false)
  682. {
  683. var list = children;
  684. var percentages = new Dictionary<Guid, double>(list.Count);
  685. var tasks = new List<Task>();
  686. foreach (var tuple in list)
  687. {
  688. if (tasks.Count > 5)
  689. {
  690. await Task.WhenAll(tasks).ConfigureAwait(false);
  691. }
  692. Tuple<BaseItem, bool> currentTuple = tuple;
  693. tasks.Add(Task.Run(async () =>
  694. {
  695. cancellationToken.ThrowIfCancellationRequested();
  696. var child = currentTuple.Item1;
  697. //refresh it
  698. await child.RefreshMetadata(cancellationToken, forceSave: currentTuple.Item2, forceRefresh: forceRefreshMetadata, resetResolveArgs: false).ConfigureAwait(false);
  699. // Refresh children if a folder and the item changed or recursive is set to true
  700. var refreshChildren = child.IsFolder && (currentTuple.Item2 || (recursive.HasValue && recursive.Value));
  701. if (refreshChildren)
  702. {
  703. // Don't refresh children if explicitly set to false
  704. if (recursive.HasValue && recursive.Value == false)
  705. {
  706. refreshChildren = false;
  707. }
  708. }
  709. if (refreshChildren)
  710. {
  711. cancellationToken.ThrowIfCancellationRequested();
  712. var innerProgress = new ActionableProgress<double>();
  713. innerProgress.RegisterAction(p =>
  714. {
  715. lock (percentages)
  716. {
  717. percentages[child.Id] = p / 100;
  718. var percent = percentages.Values.Sum();
  719. percent /= list.Count;
  720. progress.Report((90 * percent) + 10);
  721. }
  722. });
  723. await ((Folder)child).ValidateChildren(innerProgress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  724. // Some folder providers are unable to refresh until children have been refreshed.
  725. await child.RefreshMetadata(cancellationToken, resetResolveArgs: false).ConfigureAwait(false);
  726. }
  727. else
  728. {
  729. lock (percentages)
  730. {
  731. percentages[child.Id] = 1;
  732. var percent = percentages.Values.Sum();
  733. percent /= list.Count;
  734. progress.Report((90 * percent) + 10);
  735. }
  736. }
  737. }));
  738. }
  739. cancellationToken.ThrowIfCancellationRequested();
  740. await Task.WhenAll(tasks).ConfigureAwait(false);
  741. }
  742. /// <summary>
  743. /// Determines whether the specified path is offline.
  744. /// </summary>
  745. /// <param name="path">The path.</param>
  746. /// <returns><c>true</c> if the specified path is offline; otherwise, <c>false</c>.</returns>
  747. private bool IsPathOffline(string path)
  748. {
  749. if (File.Exists(path))
  750. {
  751. return false;
  752. }
  753. var originalPath = path;
  754. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  755. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  756. {
  757. if (Directory.Exists(path))
  758. {
  759. return false;
  760. }
  761. path = System.IO.Path.GetDirectoryName(path);
  762. }
  763. if (ContainsPath(LibraryManager.GetDefaultVirtualFolders(), originalPath))
  764. {
  765. return true;
  766. }
  767. return UserManager.Users.Any(user => ContainsPath(LibraryManager.GetVirtualFolders(user), originalPath));
  768. }
  769. /// <summary>
  770. /// Determines whether the specified folders contains path.
  771. /// </summary>
  772. /// <param name="folders">The folders.</param>
  773. /// <param name="path">The path.</param>
  774. /// <returns><c>true</c> if the specified folders contains path; otherwise, <c>false</c>.</returns>
  775. private bool ContainsPath(IEnumerable<VirtualFolderInfo> folders, string path)
  776. {
  777. return folders.SelectMany(i => i.Locations).Any(i => ContainsPath(i, path));
  778. }
  779. private bool ContainsPath(string parent, string path)
  780. {
  781. return string.Equals(parent, path, StringComparison.OrdinalIgnoreCase) || path.IndexOf(parent.TrimEnd(System.IO.Path.DirectorySeparatorChar) + System.IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) != -1;
  782. }
  783. /// <summary>
  784. /// Get the children of this folder from the actual file system
  785. /// </summary>
  786. /// <returns>IEnumerable{BaseItem}.</returns>
  787. protected virtual IEnumerable<BaseItem> GetNonCachedChildren()
  788. {
  789. if (ResolveArgs == null || ResolveArgs.FileSystemDictionary == null)
  790. {
  791. Logger.Error("Null for {0}", Path);
  792. }
  793. return LibraryManager.ResolvePaths<BaseItem>(ResolveArgs.FileSystemChildren, this);
  794. }
  795. /// <summary>
  796. /// Get our children from the repo - stubbed for now
  797. /// </summary>
  798. /// <returns>IEnumerable{BaseItem}.</returns>
  799. protected IEnumerable<BaseItem> GetCachedChildren()
  800. {
  801. return ItemRepository.GetChildren(Id).Select(RetrieveChild).Where(i => i != null);
  802. }
  803. /// <summary>
  804. /// Retrieves the child.
  805. /// </summary>
  806. /// <param name="child">The child.</param>
  807. /// <returns>BaseItem.</returns>
  808. private BaseItem RetrieveChild(Guid child)
  809. {
  810. var item = LibraryManager.RetrieveItem(child);
  811. if (item != null)
  812. {
  813. if (item is IByReferenceItem)
  814. {
  815. return LibraryManager.GetOrAddByReferenceItem(item);
  816. }
  817. item.Parent = this;
  818. }
  819. return item;
  820. }
  821. /// <summary>
  822. /// Gets allowed children of an item
  823. /// </summary>
  824. /// <param name="user">The user.</param>
  825. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  826. /// <param name="indexBy">The index by.</param>
  827. /// <returns>IEnumerable{BaseItem}.</returns>
  828. /// <exception cref="System.ArgumentNullException"></exception>
  829. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren, string indexBy = null)
  830. {
  831. if (user == null)
  832. {
  833. throw new ArgumentNullException();
  834. }
  835. //the true root should return our users root folder children
  836. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren, indexBy);
  837. IEnumerable<BaseItem> result = null;
  838. if (!string.IsNullOrEmpty(indexBy))
  839. {
  840. result = GetIndexedChildren(user, indexBy);
  841. }
  842. if (result != null)
  843. {
  844. return result;
  845. }
  846. var initialCount = _children.Count;
  847. var list = new List<BaseItem>(initialCount);
  848. AddChildrenToList(user, includeLinkedChildren, list, false, null);
  849. return list;
  850. }
  851. /// <summary>
  852. /// Adds the children to list.
  853. /// </summary>
  854. /// <param name="user">The user.</param>
  855. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  856. /// <param name="list">The list.</param>
  857. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  858. /// <param name="filter">The filter.</param>
  859. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  860. private bool AddChildrenToList(User user, bool includeLinkedChildren, List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  861. {
  862. var hasLinkedChildren = false;
  863. foreach (var child in Children)
  864. {
  865. if (child.IsVisible(user))
  866. {
  867. if (filter == null || filter(child))
  868. {
  869. list.Add(child);
  870. }
  871. }
  872. if (recursive)
  873. {
  874. var folder = child as Folder;
  875. if (folder != null)
  876. {
  877. if (folder.AddChildrenToList(user, includeLinkedChildren, list, true, filter))
  878. {
  879. hasLinkedChildren = true;
  880. }
  881. }
  882. }
  883. }
  884. if (includeLinkedChildren)
  885. {
  886. foreach (var child in GetLinkedChildren())
  887. {
  888. if (filter != null && !filter(child))
  889. {
  890. continue;
  891. }
  892. if (child.IsVisible(user))
  893. {
  894. hasLinkedChildren = true;
  895. list.Add(child);
  896. }
  897. }
  898. }
  899. return hasLinkedChildren;
  900. }
  901. private int _lastRecursiveCount;
  902. /// <summary>
  903. /// Gets allowed recursive children of an item
  904. /// </summary>
  905. /// <param name="user">The user.</param>
  906. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  907. /// <returns>IEnumerable{BaseItem}.</returns>
  908. /// <exception cref="System.ArgumentNullException"></exception>
  909. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  910. {
  911. return GetRecursiveChildren(user, null, includeLinkedChildren);
  912. }
  913. /// <summary>
  914. /// Gets the recursive children.
  915. /// </summary>
  916. /// <param name="user">The user.</param>
  917. /// <param name="filter">The filter.</param>
  918. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  919. /// <returns>IList{BaseItem}.</returns>
  920. /// <exception cref="System.ArgumentNullException"></exception>
  921. public IList<BaseItem> GetRecursiveChildren(User user, Func<BaseItem, bool> filter, bool includeLinkedChildren = true)
  922. {
  923. if (user == null)
  924. {
  925. throw new ArgumentNullException("user");
  926. }
  927. var initialCount = _lastRecursiveCount == 0 ? _children.Count : _lastRecursiveCount;
  928. var list = new List<BaseItem>(initialCount);
  929. var hasLinkedChildren = AddChildrenToList(user, includeLinkedChildren, list, true, filter);
  930. _lastRecursiveCount = list.Count;
  931. return hasLinkedChildren ? list.DistinctBy(i => i.Id).ToList() : list;
  932. }
  933. /// <summary>
  934. /// Gets the recursive children.
  935. /// </summary>
  936. /// <returns>IList{BaseItem}.</returns>
  937. public IList<BaseItem> GetRecursiveChildren()
  938. {
  939. return GetRecursiveChildren(i => true);
  940. }
  941. /// <summary>
  942. /// Gets the recursive children.
  943. /// </summary>
  944. /// <param name="filter">The filter.</param>
  945. /// <returns>IEnumerable{BaseItem}.</returns>
  946. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  947. {
  948. var initialCount = _lastRecursiveCount == 0 ? _children.Count : _lastRecursiveCount;
  949. var list = new List<BaseItem>(initialCount);
  950. AddChildrenToList(list, true, filter);
  951. return list;
  952. }
  953. /// <summary>
  954. /// Adds the children to list.
  955. /// </summary>
  956. /// <param name="list">The list.</param>
  957. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  958. /// <param name="filter">The filter.</param>
  959. private void AddChildrenToList(List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  960. {
  961. foreach (var child in Children)
  962. {
  963. if (filter == null || filter(child))
  964. {
  965. list.Add(child);
  966. }
  967. if (recursive)
  968. {
  969. var folder = child as Folder;
  970. if (folder != null)
  971. {
  972. folder.AddChildrenToList(list, true, filter);
  973. }
  974. }
  975. }
  976. }
  977. /// <summary>
  978. /// Gets the linked children.
  979. /// </summary>
  980. /// <returns>IEnumerable{BaseItem}.</returns>
  981. public IEnumerable<BaseItem> GetLinkedChildren()
  982. {
  983. return LinkedChildren
  984. .Select(GetLinkedChild)
  985. .Where(i => i != null);
  986. }
  987. /// <summary>
  988. /// Gets the linked child.
  989. /// </summary>
  990. /// <param name="info">The info.</param>
  991. /// <returns>BaseItem.</returns>
  992. private BaseItem GetLinkedChild(LinkedChild info)
  993. {
  994. if (string.IsNullOrEmpty(info.Path))
  995. {
  996. throw new ArgumentException("Encountered linked child with empty path.");
  997. }
  998. BaseItem item = null;
  999. // First get using the cached Id
  1000. if (info.ItemId != Guid.Empty)
  1001. {
  1002. item = LibraryManager.GetItemById(info.ItemId);
  1003. }
  1004. // If still null, search by path
  1005. if (item == null)
  1006. {
  1007. item = LibraryManager.RootFolder.FindByPath(info.Path);
  1008. }
  1009. // If still null, log
  1010. if (item == null)
  1011. {
  1012. Logger.Warn("Unable to find linked item at {0}", info.Path);
  1013. }
  1014. else
  1015. {
  1016. // Cache the id for next time
  1017. info.ItemId = item.Id;
  1018. }
  1019. return item;
  1020. }
  1021. public override async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  1022. {
  1023. var changed = await base.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs).ConfigureAwait(false);
  1024. return changed || (SupportsShortcutChildren && LocationType == LocationType.FileSystem && RefreshLinkedChildren());
  1025. }
  1026. /// <summary>
  1027. /// Refreshes the linked children.
  1028. /// </summary>
  1029. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1030. private bool RefreshLinkedChildren()
  1031. {
  1032. ItemResolveArgs resolveArgs;
  1033. try
  1034. {
  1035. resolveArgs = ResolveArgs;
  1036. if (!resolveArgs.IsDirectory)
  1037. {
  1038. return false;
  1039. }
  1040. }
  1041. catch (IOException ex)
  1042. {
  1043. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1044. return false;
  1045. }
  1046. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  1047. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1048. var newShortcutLinks = resolveArgs.FileSystemChildren
  1049. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  1050. .Select(i =>
  1051. {
  1052. try
  1053. {
  1054. Logger.Debug("Found shortcut at {0}", i.FullName);
  1055. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  1056. if (!string.IsNullOrEmpty(resolvedPath))
  1057. {
  1058. return new LinkedChild
  1059. {
  1060. Path = resolvedPath,
  1061. Type = LinkedChildType.Shortcut
  1062. };
  1063. }
  1064. Logger.Error("Error resolving shortcut {0}", i.FullName);
  1065. return null;
  1066. }
  1067. catch (IOException ex)
  1068. {
  1069. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  1070. return null;
  1071. }
  1072. })
  1073. .Where(i => i != null)
  1074. .ToList();
  1075. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  1076. {
  1077. Logger.Info("Shortcut links have changed for {0}", Path);
  1078. newShortcutLinks.AddRange(currentManualLinks);
  1079. LinkedChildren = newShortcutLinks;
  1080. return true;
  1081. }
  1082. return false;
  1083. }
  1084. /// <summary>
  1085. /// Folders need to validate and refresh
  1086. /// </summary>
  1087. /// <returns>Task.</returns>
  1088. public override async Task ChangedExternally()
  1089. {
  1090. await base.ChangedExternally().ConfigureAwait(false);
  1091. var progress = new Progress<double>();
  1092. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  1093. }
  1094. /// <summary>
  1095. /// Marks the played.
  1096. /// </summary>
  1097. /// <param name="user">The user.</param>
  1098. /// <param name="datePlayed">The date played.</param>
  1099. /// <param name="userManager">The user manager.</param>
  1100. /// <returns>Task.</returns>
  1101. public override async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataManager userManager)
  1102. {
  1103. // Sweep through recursively and update status
  1104. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder).Select(c => c.MarkPlayed(user, datePlayed, userManager));
  1105. await Task.WhenAll(tasks).ConfigureAwait(false);
  1106. }
  1107. /// <summary>
  1108. /// Marks the unplayed.
  1109. /// </summary>
  1110. /// <param name="user">The user.</param>
  1111. /// <param name="userManager">The user manager.</param>
  1112. /// <returns>Task.</returns>
  1113. public override async Task MarkUnplayed(User user, IUserDataManager userManager)
  1114. {
  1115. // Sweep through recursively and update status
  1116. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder).Select(c => c.MarkUnplayed(user, userManager));
  1117. await Task.WhenAll(tasks).ConfigureAwait(false);
  1118. }
  1119. /// <summary>
  1120. /// Finds an item by path, recursively
  1121. /// </summary>
  1122. /// <param name="path">The path.</param>
  1123. /// <returns>BaseItem.</returns>
  1124. /// <exception cref="System.ArgumentNullException"></exception>
  1125. public BaseItem FindByPath(string path)
  1126. {
  1127. if (string.IsNullOrEmpty(path))
  1128. {
  1129. throw new ArgumentNullException();
  1130. }
  1131. try
  1132. {
  1133. if (ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1134. {
  1135. return this;
  1136. }
  1137. }
  1138. catch (IOException ex)
  1139. {
  1140. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1141. }
  1142. //this should be functionally equivilent to what was here since it is IEnum and works on a thread-safe copy
  1143. return RecursiveChildren.FirstOrDefault(i =>
  1144. {
  1145. try
  1146. {
  1147. return i.ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase);
  1148. }
  1149. catch (IOException ex)
  1150. {
  1151. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1152. return false;
  1153. }
  1154. });
  1155. }
  1156. }
  1157. }