Folder.cs 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  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 > 7)
  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. try
  698. {
  699. //refresh it
  700. await child.RefreshMetadata(cancellationToken, forceSave: currentTuple.Item2, forceRefresh: forceRefreshMetadata, resetResolveArgs: false).ConfigureAwait(false);
  701. }
  702. catch (IOException ex)
  703. {
  704. Logger.ErrorException("Error refreshing {0}", ex, child.Path ?? child.Name);
  705. }
  706. // Refresh children if a folder and the item changed or recursive is set to true
  707. var refreshChildren = child.IsFolder && (currentTuple.Item2 || (recursive.HasValue && recursive.Value));
  708. if (refreshChildren)
  709. {
  710. // Don't refresh children if explicitly set to false
  711. if (recursive.HasValue && recursive.Value == false)
  712. {
  713. refreshChildren = false;
  714. }
  715. }
  716. if (refreshChildren)
  717. {
  718. cancellationToken.ThrowIfCancellationRequested();
  719. var innerProgress = new ActionableProgress<double>();
  720. innerProgress.RegisterAction(p =>
  721. {
  722. lock (percentages)
  723. {
  724. percentages[child.Id] = p / 100;
  725. var percent = percentages.Values.Sum();
  726. percent /= list.Count;
  727. progress.Report((90 * percent) + 10);
  728. }
  729. });
  730. await ((Folder)child).ValidateChildren(innerProgress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  731. try
  732. {
  733. // Some folder providers are unable to refresh until children have been refreshed.
  734. await child.RefreshMetadata(cancellationToken, resetResolveArgs: false).ConfigureAwait(false);
  735. }
  736. catch (IOException ex)
  737. {
  738. Logger.ErrorException("Error refreshing {0}", ex, child.Path ?? child.Name);
  739. }
  740. }
  741. else
  742. {
  743. lock (percentages)
  744. {
  745. percentages[child.Id] = 1;
  746. var percent = percentages.Values.Sum();
  747. percent /= list.Count;
  748. progress.Report((90 * percent) + 10);
  749. }
  750. }
  751. }));
  752. }
  753. cancellationToken.ThrowIfCancellationRequested();
  754. await Task.WhenAll(tasks).ConfigureAwait(false);
  755. }
  756. /// <summary>
  757. /// Determines whether the specified path is offline.
  758. /// </summary>
  759. /// <param name="path">The path.</param>
  760. /// <returns><c>true</c> if the specified path is offline; otherwise, <c>false</c>.</returns>
  761. private bool IsPathOffline(string path)
  762. {
  763. if (File.Exists(path))
  764. {
  765. return false;
  766. }
  767. var originalPath = path;
  768. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  769. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  770. {
  771. if (Directory.Exists(path))
  772. {
  773. return false;
  774. }
  775. path = System.IO.Path.GetDirectoryName(path);
  776. }
  777. if (ContainsPath(LibraryManager.GetDefaultVirtualFolders(), originalPath))
  778. {
  779. return true;
  780. }
  781. return UserManager.Users.Any(user => ContainsPath(LibraryManager.GetVirtualFolders(user), originalPath));
  782. }
  783. /// <summary>
  784. /// Determines whether the specified folders contains path.
  785. /// </summary>
  786. /// <param name="folders">The folders.</param>
  787. /// <param name="path">The path.</param>
  788. /// <returns><c>true</c> if the specified folders contains path; otherwise, <c>false</c>.</returns>
  789. private bool ContainsPath(IEnumerable<VirtualFolderInfo> folders, string path)
  790. {
  791. return folders.SelectMany(i => i.Locations).Any(i => ContainsPath(i, path));
  792. }
  793. private bool ContainsPath(string parent, string path)
  794. {
  795. return string.Equals(parent, path, StringComparison.OrdinalIgnoreCase) || path.IndexOf(parent.TrimEnd(System.IO.Path.DirectorySeparatorChar) + System.IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) != -1;
  796. }
  797. /// <summary>
  798. /// Get the children of this folder from the actual file system
  799. /// </summary>
  800. /// <returns>IEnumerable{BaseItem}.</returns>
  801. protected virtual IEnumerable<BaseItem> GetNonCachedChildren()
  802. {
  803. if (ResolveArgs == null || ResolveArgs.FileSystemDictionary == null)
  804. {
  805. Logger.Error("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)
  887. {
  888. var folder = child as Folder;
  889. if (folder != null)
  890. {
  891. if (folder.AddChildrenToList(user, includeLinkedChildren, list, true, filter))
  892. {
  893. hasLinkedChildren = true;
  894. }
  895. }
  896. }
  897. }
  898. if (includeLinkedChildren)
  899. {
  900. foreach (var child in GetLinkedChildren())
  901. {
  902. if (filter != null && !filter(child))
  903. {
  904. continue;
  905. }
  906. if (child.IsVisible(user))
  907. {
  908. hasLinkedChildren = true;
  909. list.Add(child);
  910. }
  911. }
  912. }
  913. return hasLinkedChildren;
  914. }
  915. private int _lastRecursiveCount;
  916. /// <summary>
  917. /// Gets allowed recursive children of an item
  918. /// </summary>
  919. /// <param name="user">The user.</param>
  920. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  921. /// <returns>IEnumerable{BaseItem}.</returns>
  922. /// <exception cref="System.ArgumentNullException"></exception>
  923. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  924. {
  925. return GetRecursiveChildren(user, null, includeLinkedChildren);
  926. }
  927. /// <summary>
  928. /// Gets the recursive children.
  929. /// </summary>
  930. /// <param name="user">The user.</param>
  931. /// <param name="filter">The filter.</param>
  932. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  933. /// <returns>IList{BaseItem}.</returns>
  934. /// <exception cref="System.ArgumentNullException"></exception>
  935. public IList<BaseItem> GetRecursiveChildren(User user, Func<BaseItem, bool> filter, bool includeLinkedChildren = true)
  936. {
  937. if (user == null)
  938. {
  939. throw new ArgumentNullException("user");
  940. }
  941. var initialCount = _lastRecursiveCount == 0 ? _children.Count : _lastRecursiveCount;
  942. var list = new List<BaseItem>(initialCount);
  943. var hasLinkedChildren = AddChildrenToList(user, includeLinkedChildren, list, true, filter);
  944. _lastRecursiveCount = list.Count;
  945. return hasLinkedChildren ? list.DistinctBy(i => i.Id).ToList() : list;
  946. }
  947. /// <summary>
  948. /// Gets the recursive children.
  949. /// </summary>
  950. /// <returns>IList{BaseItem}.</returns>
  951. public IList<BaseItem> GetRecursiveChildren()
  952. {
  953. return GetRecursiveChildren(i => true);
  954. }
  955. /// <summary>
  956. /// Gets the recursive children.
  957. /// </summary>
  958. /// <param name="filter">The filter.</param>
  959. /// <returns>IEnumerable{BaseItem}.</returns>
  960. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  961. {
  962. var initialCount = _lastRecursiveCount == 0 ? _children.Count : _lastRecursiveCount;
  963. var list = new List<BaseItem>(initialCount);
  964. AddChildrenToList(list, true, filter);
  965. return list;
  966. }
  967. /// <summary>
  968. /// Adds the children to list.
  969. /// </summary>
  970. /// <param name="list">The list.</param>
  971. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  972. /// <param name="filter">The filter.</param>
  973. private void AddChildrenToList(List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  974. {
  975. foreach (var child in Children)
  976. {
  977. if (filter == null || filter(child))
  978. {
  979. list.Add(child);
  980. }
  981. if (recursive)
  982. {
  983. var folder = child as Folder;
  984. if (folder != null)
  985. {
  986. folder.AddChildrenToList(list, true, filter);
  987. }
  988. }
  989. }
  990. }
  991. /// <summary>
  992. /// Gets the linked children.
  993. /// </summary>
  994. /// <returns>IEnumerable{BaseItem}.</returns>
  995. public IEnumerable<BaseItem> GetLinkedChildren()
  996. {
  997. return LinkedChildren
  998. .Select(GetLinkedChild)
  999. .Where(i => i != null);
  1000. }
  1001. /// <summary>
  1002. /// Gets the linked child.
  1003. /// </summary>
  1004. /// <param name="info">The info.</param>
  1005. /// <returns>BaseItem.</returns>
  1006. private BaseItem GetLinkedChild(LinkedChild info)
  1007. {
  1008. if (string.IsNullOrEmpty(info.Path))
  1009. {
  1010. throw new ArgumentException("Encountered linked child with empty path.");
  1011. }
  1012. BaseItem item = null;
  1013. // First get using the cached Id
  1014. if (info.ItemId != Guid.Empty)
  1015. {
  1016. item = LibraryManager.GetItemById(info.ItemId);
  1017. }
  1018. // If still null, search by path
  1019. if (item == null)
  1020. {
  1021. item = LibraryManager.RootFolder.FindByPath(info.Path);
  1022. }
  1023. // If still null, log
  1024. if (item == null)
  1025. {
  1026. Logger.Warn("Unable to find linked item at {0}", info.Path);
  1027. }
  1028. else
  1029. {
  1030. // Cache the id for next time
  1031. info.ItemId = item.Id;
  1032. }
  1033. return item;
  1034. }
  1035. public override async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  1036. {
  1037. var changed = await base.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs).ConfigureAwait(false);
  1038. return changed || (SupportsShortcutChildren && LocationType == LocationType.FileSystem && RefreshLinkedChildren());
  1039. }
  1040. /// <summary>
  1041. /// Refreshes the linked children.
  1042. /// </summary>
  1043. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1044. private bool RefreshLinkedChildren()
  1045. {
  1046. ItemResolveArgs resolveArgs;
  1047. try
  1048. {
  1049. resolveArgs = ResolveArgs;
  1050. if (!resolveArgs.IsDirectory)
  1051. {
  1052. return false;
  1053. }
  1054. }
  1055. catch (IOException ex)
  1056. {
  1057. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1058. return false;
  1059. }
  1060. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  1061. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1062. var newShortcutLinks = resolveArgs.FileSystemChildren
  1063. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  1064. .Select(i =>
  1065. {
  1066. try
  1067. {
  1068. Logger.Debug("Found shortcut at {0}", i.FullName);
  1069. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  1070. if (!string.IsNullOrEmpty(resolvedPath))
  1071. {
  1072. return new LinkedChild
  1073. {
  1074. Path = resolvedPath,
  1075. Type = LinkedChildType.Shortcut
  1076. };
  1077. }
  1078. Logger.Error("Error resolving shortcut {0}", i.FullName);
  1079. return null;
  1080. }
  1081. catch (IOException ex)
  1082. {
  1083. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  1084. return null;
  1085. }
  1086. })
  1087. .Where(i => i != null)
  1088. .ToList();
  1089. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  1090. {
  1091. Logger.Info("Shortcut links have changed for {0}", Path);
  1092. newShortcutLinks.AddRange(currentManualLinks);
  1093. LinkedChildren = newShortcutLinks;
  1094. return true;
  1095. }
  1096. return false;
  1097. }
  1098. /// <summary>
  1099. /// Folders need to validate and refresh
  1100. /// </summary>
  1101. /// <returns>Task.</returns>
  1102. public override async Task ChangedExternally()
  1103. {
  1104. await base.ChangedExternally().ConfigureAwait(false);
  1105. var progress = new Progress<double>();
  1106. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  1107. }
  1108. /// <summary>
  1109. /// Marks the played.
  1110. /// </summary>
  1111. /// <param name="user">The user.</param>
  1112. /// <param name="datePlayed">The date played.</param>
  1113. /// <param name="userManager">The user manager.</param>
  1114. /// <returns>Task.</returns>
  1115. public override async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataManager userManager)
  1116. {
  1117. // Sweep through recursively and update status
  1118. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder).Select(c => c.MarkPlayed(user, datePlayed, userManager));
  1119. await Task.WhenAll(tasks).ConfigureAwait(false);
  1120. }
  1121. /// <summary>
  1122. /// Marks the unplayed.
  1123. /// </summary>
  1124. /// <param name="user">The user.</param>
  1125. /// <param name="userManager">The user manager.</param>
  1126. /// <returns>Task.</returns>
  1127. public override async Task MarkUnplayed(User user, IUserDataManager userManager)
  1128. {
  1129. // Sweep through recursively and update status
  1130. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder).Select(c => c.MarkUnplayed(user, userManager));
  1131. await Task.WhenAll(tasks).ConfigureAwait(false);
  1132. }
  1133. /// <summary>
  1134. /// Finds an item by path, recursively
  1135. /// </summary>
  1136. /// <param name="path">The path.</param>
  1137. /// <returns>BaseItem.</returns>
  1138. /// <exception cref="System.ArgumentNullException"></exception>
  1139. public BaseItem FindByPath(string path)
  1140. {
  1141. if (string.IsNullOrEmpty(path))
  1142. {
  1143. throw new ArgumentNullException();
  1144. }
  1145. try
  1146. {
  1147. if (LocationType == LocationType.Remote && string.Equals(Path, path, StringComparison.OrdinalIgnoreCase))
  1148. {
  1149. return this;
  1150. }
  1151. if (LocationType != LocationType.Virtual && ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1152. {
  1153. return this;
  1154. }
  1155. }
  1156. catch (IOException ex)
  1157. {
  1158. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1159. }
  1160. //this should be functionally equivilent to what was here since it is IEnum and works on a thread-safe copy
  1161. return RecursiveChildren.Where(i => i.LocationType != LocationType.Virtual).FirstOrDefault(i =>
  1162. {
  1163. if (i.LocationType == LocationType.Remote)
  1164. {
  1165. return string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase);
  1166. }
  1167. try
  1168. {
  1169. return i.ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase);
  1170. }
  1171. catch (IOException ex)
  1172. {
  1173. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1174. return false;
  1175. }
  1176. });
  1177. }
  1178. }
  1179. }