Folder.cs 52 KB

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