Folder.cs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.Progress;
  3. using MediaBrowser.Controller.Entities.TV;
  4. using MediaBrowser.Controller.IO;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Localization;
  7. using MediaBrowser.Controller.Resolvers;
  8. using MediaBrowser.Model.Entities;
  9. using MoreLinq;
  10. using System;
  11. using System.Collections;
  12. using System.Collections.Concurrent;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Runtime.Serialization;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Controller.Entities
  20. {
  21. /// <summary>
  22. /// Class Folder
  23. /// </summary>
  24. public class Folder : BaseItem
  25. {
  26. public static IUserManager UserManager { get; set; }
  27. public Folder()
  28. {
  29. LinkedChildren = new List<LinkedChild>();
  30. }
  31. /// <summary>
  32. /// Gets a value indicating whether this instance is folder.
  33. /// </summary>
  34. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  35. [IgnoreDataMember]
  36. public override bool IsFolder
  37. {
  38. get
  39. {
  40. return true;
  41. }
  42. }
  43. /// <summary>
  44. /// Gets or sets a value indicating whether this instance is physical root.
  45. /// </summary>
  46. /// <value><c>true</c> if this instance is physical root; otherwise, <c>false</c>.</value>
  47. public bool IsPhysicalRoot { get; set; }
  48. /// <summary>
  49. /// Gets or sets a value indicating whether this instance is root.
  50. /// </summary>
  51. /// <value><c>true</c> if this instance is root; otherwise, <c>false</c>.</value>
  52. public bool IsRoot { get; set; }
  53. /// <summary>
  54. /// Gets a value indicating whether this instance is virtual folder.
  55. /// </summary>
  56. /// <value><c>true</c> if this instance is virtual folder; otherwise, <c>false</c>.</value>
  57. [IgnoreDataMember]
  58. public virtual bool IsVirtualFolder
  59. {
  60. get
  61. {
  62. return false;
  63. }
  64. }
  65. public virtual List<LinkedChild> LinkedChildren { get; set; }
  66. protected virtual bool SupportsShortcutChildren
  67. {
  68. get { return true; }
  69. }
  70. /// <summary>
  71. /// Adds the child.
  72. /// </summary>
  73. /// <param name="item">The item.</param>
  74. /// <param name="cancellationToken">The cancellation token.</param>
  75. /// <returns>Task.</returns>
  76. /// <exception cref="System.InvalidOperationException">Unable to add + item.Name</exception>
  77. public async Task AddChild(BaseItem item, CancellationToken cancellationToken)
  78. {
  79. item.Parent = this;
  80. if (item.Id == Guid.Empty)
  81. {
  82. item.Id = item.Path.GetMBId(item.GetType());
  83. }
  84. if (_children.Any(i => i.Id == item.Id))
  85. {
  86. throw new ArgumentException(string.Format("A child with the Id {0} already exists.", item.Id));
  87. }
  88. if (item.DateCreated == DateTime.MinValue)
  89. {
  90. item.DateCreated = DateTime.UtcNow;
  91. }
  92. if (item.DateModified == DateTime.MinValue)
  93. {
  94. item.DateModified = DateTime.UtcNow;
  95. }
  96. AddChildInternal(item);
  97. await LibraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  98. await ItemRepository.SaveChildren(Id, _children.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  99. }
  100. protected void AddChildrenInternal(IEnumerable<BaseItem> children)
  101. {
  102. lock (_childrenSyncLock)
  103. {
  104. var newChildren = _children.ToList();
  105. newChildren.AddRange(children);
  106. _children = newChildren;
  107. }
  108. }
  109. protected void AddChildInternal(BaseItem child)
  110. {
  111. lock (_childrenSyncLock)
  112. {
  113. var newChildren = _children.ToList();
  114. newChildren.Add(child);
  115. _children = newChildren;
  116. }
  117. }
  118. protected void RemoveChildrenInternal(IEnumerable<BaseItem> children)
  119. {
  120. lock (_childrenSyncLock)
  121. {
  122. _children = _children.Except(children).ToList();
  123. }
  124. }
  125. protected void ClearChildrenInternal()
  126. {
  127. lock (_childrenSyncLock)
  128. {
  129. _children = new List<BaseItem>();
  130. }
  131. }
  132. /// <summary>
  133. /// Never want folders to be blocked by "BlockNotRated"
  134. /// </summary>
  135. [IgnoreDataMember]
  136. public override string OfficialRatingForComparison
  137. {
  138. get
  139. {
  140. if (this is Series)
  141. {
  142. return base.OfficialRatingForComparison;
  143. }
  144. return !string.IsNullOrEmpty(base.OfficialRatingForComparison) ? base.OfficialRatingForComparison : "None";
  145. }
  146. }
  147. /// <summary>
  148. /// Removes the child.
  149. /// </summary>
  150. /// <param name="item">The item.</param>
  151. /// <param name="cancellationToken">The cancellation token.</param>
  152. /// <returns>Task.</returns>
  153. /// <exception cref="System.InvalidOperationException">Unable to remove + item.Name</exception>
  154. public Task RemoveChild(BaseItem item, CancellationToken cancellationToken)
  155. {
  156. RemoveChildrenInternal(new[] { item });
  157. item.Parent = null;
  158. LibraryManager.ReportItemRemoved(item);
  159. return ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken);
  160. }
  161. /// <summary>
  162. /// Clears the children.
  163. /// </summary>
  164. /// <param name="cancellationToken">The cancellation token.</param>
  165. /// <returns>Task.</returns>
  166. public Task ClearChildren(CancellationToken cancellationToken)
  167. {
  168. var items = ActualChildren.ToList();
  169. ClearChildrenInternal();
  170. foreach (var item in items)
  171. {
  172. LibraryManager.ReportItemRemoved(item);
  173. }
  174. return ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken);
  175. }
  176. #region Indexing
  177. /// <summary>
  178. /// The _index by options
  179. /// </summary>
  180. private Dictionary<string, Func<User, IEnumerable<BaseItem>>> _indexByOptions;
  181. /// <summary>
  182. /// Dictionary of index options - consists of a display value and an indexing function
  183. /// which takes User as a parameter and returns an IEnum of BaseItem
  184. /// </summary>
  185. /// <value>The index by options.</value>
  186. [IgnoreDataMember]
  187. public Dictionary<string, Func<User, IEnumerable<BaseItem>>> IndexByOptions
  188. {
  189. get { return _indexByOptions ?? (_indexByOptions = GetIndexByOptions()); }
  190. }
  191. /// <summary>
  192. /// Returns the valid set of index by options for this folder type.
  193. /// Override or extend to modify.
  194. /// </summary>
  195. /// <returns>Dictionary{System.StringFunc{UserIEnumerable{BaseItem}}}.</returns>
  196. protected virtual Dictionary<string, Func<User, IEnumerable<BaseItem>>> GetIndexByOptions()
  197. {
  198. return new Dictionary<string, Func<User, IEnumerable<BaseItem>>> {
  199. {LocalizedStrings.Instance.GetString("NoneDispPref"), null},
  200. {LocalizedStrings.Instance.GetString("PerformerDispPref"), GetIndexByPerformer},
  201. {LocalizedStrings.Instance.GetString("GenreDispPref"), GetIndexByGenre},
  202. {LocalizedStrings.Instance.GetString("DirectorDispPref"), GetIndexByDirector},
  203. {LocalizedStrings.Instance.GetString("YearDispPref"), GetIndexByYear},
  204. //{LocalizedStrings.Instance.GetString("OfficialRatingDispPref"), null},
  205. {LocalizedStrings.Instance.GetString("StudioDispPref"), GetIndexByStudio}
  206. };
  207. }
  208. /// <summary>
  209. /// Gets the index by actor.
  210. /// </summary>
  211. /// <param name="user">The user.</param>
  212. /// <returns>IEnumerable{BaseItem}.</returns>
  213. protected IEnumerable<BaseItem> GetIndexByPerformer(User user)
  214. {
  215. return GetIndexByPerson(user, new List<string> { PersonType.Actor, PersonType.GuestStar }, true, LocalizedStrings.Instance.GetString("PerformerDispPref"));
  216. }
  217. /// <summary>
  218. /// Gets the index by director.
  219. /// </summary>
  220. /// <param name="user">The user.</param>
  221. /// <returns>IEnumerable{BaseItem}.</returns>
  222. protected IEnumerable<BaseItem> GetIndexByDirector(User user)
  223. {
  224. return GetIndexByPerson(user, new List<string> { PersonType.Director }, false, LocalizedStrings.Instance.GetString("DirectorDispPref"));
  225. }
  226. /// <summary>
  227. /// Gets the index by person.
  228. /// </summary>
  229. /// <param name="user">The user.</param>
  230. /// <param name="personTypes">The person types we should match on</param>
  231. /// <param name="includeAudio">if set to <c>true</c> [include audio].</param>
  232. /// <param name="indexName">Name of the index.</param>
  233. /// <returns>IEnumerable{BaseItem}.</returns>
  234. private IEnumerable<BaseItem> GetIndexByPerson(User user, List<string> personTypes, bool includeAudio, string indexName)
  235. {
  236. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  237. // the retrieval of the individual children for each index value until they are requested.
  238. using (new Profiler(indexName + " Index Build for " + Name, Logger))
  239. {
  240. // Put this in a local variable to avoid an implicitly captured closure
  241. var currentIndexName = indexName;
  242. var us = this;
  243. var recursiveChildren = GetRecursiveChildren(user).Where(i => i.IncludeInIndex).ToList();
  244. // Get the candidates, but handle audio separately
  245. var candidates = recursiveChildren.Where(i => i.AllPeople != null && !(i is Audio.Audio)).ToList();
  246. var indexFolders = candidates.AsParallel().SelectMany(i => i.AllPeople.Where(p => personTypes.Contains(p.Type))
  247. .Select(a => a.Name))
  248. .Distinct()
  249. .Select(i =>
  250. {
  251. try
  252. {
  253. return LibraryManager.GetPerson(i);
  254. }
  255. catch (IOException ex)
  256. {
  257. Logger.ErrorException("Error getting person {0}", ex, i);
  258. return null;
  259. }
  260. catch (AggregateException ex)
  261. {
  262. Logger.ErrorException("Error getting person {0}", ex, i);
  263. return null;
  264. }
  265. })
  266. .Where(i => i != null)
  267. .Select(a => new IndexFolder(us, a,
  268. candidates.Where(i => i.AllPeople.Any(p => personTypes.Contains(p.Type) && p.Name.Equals(a.Name, StringComparison.OrdinalIgnoreCase))
  269. ), currentIndexName)).AsEnumerable();
  270. if (includeAudio)
  271. {
  272. var songs = recursiveChildren.OfType<Audio.Audio>().ToList();
  273. indexFolders = songs.SelectMany(i => i.Artists)
  274. .Distinct(StringComparer.OrdinalIgnoreCase)
  275. .Select(i =>
  276. {
  277. try
  278. {
  279. return LibraryManager.GetArtist(i);
  280. }
  281. catch (IOException ex)
  282. {
  283. Logger.ErrorException("Error getting artist {0}", ex, i);
  284. return null;
  285. }
  286. catch (AggregateException ex)
  287. {
  288. Logger.ErrorException("Error getting artist {0}", ex, i);
  289. return null;
  290. }
  291. })
  292. .Where(i => i != null)
  293. .Select(a => new IndexFolder(us, a,
  294. songs.Where(i => i.Artists.Contains(a.Name, StringComparer.OrdinalIgnoreCase)
  295. ), currentIndexName)).Concat(indexFolders);
  296. }
  297. return indexFolders;
  298. }
  299. }
  300. /// <summary>
  301. /// Gets the index by studio.
  302. /// </summary>
  303. /// <param name="user">The user.</param>
  304. /// <returns>IEnumerable{BaseItem}.</returns>
  305. protected IEnumerable<BaseItem> GetIndexByStudio(User user)
  306. {
  307. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  308. // the retrieval of the individual children for each index value until they are requested.
  309. using (new Profiler("Studio Index Build for " + Name, Logger))
  310. {
  311. var indexName = LocalizedStrings.Instance.GetString("StudioDispPref");
  312. var candidates = GetRecursiveChildren(user).Where(i => i.IncludeInIndex).ToList();
  313. return candidates.AsParallel().SelectMany(i => i.AllStudios)
  314. .Distinct()
  315. .Select(i =>
  316. {
  317. try
  318. {
  319. return LibraryManager.GetStudio(i);
  320. }
  321. catch (IOException ex)
  322. {
  323. Logger.ErrorException("Error getting studio {0}", ex, i);
  324. return null;
  325. }
  326. catch (AggregateException ex)
  327. {
  328. Logger.ErrorException("Error getting studio {0}", ex, i);
  329. return null;
  330. }
  331. })
  332. .Where(i => i != null)
  333. .Select(ndx => new IndexFolder(this, ndx, candidates.Where(i => i.AllStudios.Any(s => s.Equals(ndx.Name, StringComparison.OrdinalIgnoreCase))), indexName));
  334. }
  335. }
  336. /// <summary>
  337. /// Gets the index by genre.
  338. /// </summary>
  339. /// <param name="user">The user.</param>
  340. /// <returns>IEnumerable{BaseItem}.</returns>
  341. protected IEnumerable<BaseItem> GetIndexByGenre(User user)
  342. {
  343. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  344. // the retrieval of the individual children for each index value until they are requested.
  345. using (new Profiler("Genre Index Build for " + Name, Logger))
  346. {
  347. var indexName = LocalizedStrings.Instance.GetString("GenreDispPref");
  348. //we need a copy of this so we don't double-recurse
  349. var candidates = GetRecursiveChildren(user).Where(i => i.IncludeInIndex).ToList();
  350. return candidates.AsParallel().SelectMany(i => i.AllGenres)
  351. .Distinct(StringComparer.OrdinalIgnoreCase)
  352. .Select(i =>
  353. {
  354. try
  355. {
  356. return LibraryManager.GetGenre(i);
  357. }
  358. catch (Exception ex)
  359. {
  360. Logger.ErrorException("Error getting genre {0}", ex, i);
  361. return null;
  362. }
  363. })
  364. .Where(i => i != null)
  365. .Select(genre => new IndexFolder(this, genre, candidates.Where(i => i.AllGenres.Any(g => g.Equals(genre.Name, StringComparison.OrdinalIgnoreCase))), indexName)
  366. );
  367. }
  368. }
  369. /// <summary>
  370. /// Gets the index by year.
  371. /// </summary>
  372. /// <param name="user">The user.</param>
  373. /// <returns>IEnumerable{BaseItem}.</returns>
  374. protected IEnumerable<BaseItem> GetIndexByYear(User user)
  375. {
  376. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  377. // the retrieval of the individual children for each index value until they are requested.
  378. using (new Profiler("Production Year Index Build for " + Name, Logger))
  379. {
  380. var indexName = LocalizedStrings.Instance.GetString("YearDispPref");
  381. //we need a copy of this so we don't double-recurse
  382. var candidates = GetRecursiveChildren(user).Where(i => i.IncludeInIndex && i.ProductionYear.HasValue).ToList();
  383. return candidates.AsParallel().Select(i => i.ProductionYear.Value)
  384. .Distinct()
  385. .Select(i =>
  386. {
  387. try
  388. {
  389. return LibraryManager.GetYear(i);
  390. }
  391. catch (IOException ex)
  392. {
  393. Logger.ErrorException("Error getting year {0}", ex, i);
  394. return null;
  395. }
  396. catch (AggregateException ex)
  397. {
  398. Logger.ErrorException("Error getting year {0}", ex, i);
  399. return null;
  400. }
  401. })
  402. .Where(i => i != null)
  403. .Select(ndx => new IndexFolder(this, ndx, candidates.Where(i => i.ProductionYear == int.Parse(ndx.Name)), indexName));
  404. }
  405. }
  406. /// <summary>
  407. /// Returns the indexed children for this user from the cache. Caches them if not already there.
  408. /// </summary>
  409. /// <param name="user">The user.</param>
  410. /// <param name="indexBy">The index by.</param>
  411. /// <returns>IEnumerable{BaseItem}.</returns>
  412. private IEnumerable<BaseItem> GetIndexedChildren(User user, string indexBy)
  413. {
  414. List<BaseItem> result = null;
  415. var cacheKey = user.Name + indexBy;
  416. if (IndexCache != null)
  417. {
  418. IndexCache.TryGetValue(cacheKey, out result);
  419. }
  420. if (result == null)
  421. {
  422. //not cached - cache it
  423. Func<User, IEnumerable<BaseItem>> indexing;
  424. IndexByOptions.TryGetValue(indexBy, out indexing);
  425. result = BuildIndex(indexBy, indexing, user);
  426. }
  427. return result;
  428. }
  429. /// <summary>
  430. /// Get the list of indexy by choices for this folder (localized).
  431. /// </summary>
  432. /// <value>The index by option strings.</value>
  433. [IgnoreDataMember]
  434. public IEnumerable<string> IndexByOptionStrings
  435. {
  436. get { return IndexByOptions.Keys; }
  437. }
  438. /// <summary>
  439. /// The index cache
  440. /// </summary>
  441. protected ConcurrentDictionary<string, List<BaseItem>> IndexCache;
  442. /// <summary>
  443. /// Builds the index.
  444. /// </summary>
  445. /// <param name="indexKey">The index key.</param>
  446. /// <param name="indexFunction">The index function.</param>
  447. /// <param name="user">The user.</param>
  448. /// <returns>List{BaseItem}.</returns>
  449. protected virtual List<BaseItem> BuildIndex(string indexKey, Func<User, IEnumerable<BaseItem>> indexFunction, User user)
  450. {
  451. if (IndexCache == null)
  452. {
  453. IndexCache = new ConcurrentDictionary<string, List<BaseItem>>();
  454. }
  455. return indexFunction != null
  456. ? IndexCache[user.Name + indexKey] = indexFunction(user).ToList()
  457. : null;
  458. }
  459. #endregion
  460. /// <summary>
  461. /// The children
  462. /// </summary>
  463. private IReadOnlyList<BaseItem> _children = new List<BaseItem>();
  464. /// <summary>
  465. /// The _children sync lock
  466. /// </summary>
  467. private readonly object _childrenSyncLock = new object();
  468. /// <summary>
  469. /// Gets or sets the actual children.
  470. /// </summary>
  471. /// <value>The actual children.</value>
  472. protected virtual IEnumerable<BaseItem> ActualChildren
  473. {
  474. get
  475. {
  476. return _children;
  477. }
  478. }
  479. public void LoadSavedChildren()
  480. {
  481. _children = LoadChildrenInternal();
  482. }
  483. /// <summary>
  484. /// thread-safe access to the actual children of this folder - without regard to user
  485. /// </summary>
  486. /// <value>The children.</value>
  487. [IgnoreDataMember]
  488. public IEnumerable<BaseItem> Children
  489. {
  490. get { return ActualChildren; }
  491. }
  492. /// <summary>
  493. /// thread-safe access to all recursive children of this folder - without regard to user
  494. /// </summary>
  495. /// <value>The recursive children.</value>
  496. [IgnoreDataMember]
  497. public IEnumerable<BaseItem> RecursiveChildren
  498. {
  499. get { return GetRecursiveChildren(); }
  500. }
  501. private List<BaseItem> LoadChildrenInternal()
  502. {
  503. return LoadChildren().ToList();
  504. }
  505. /// <summary>
  506. /// Loads our children. Validation will occur externally.
  507. /// We want this sychronous.
  508. /// </summary>
  509. protected virtual IEnumerable<BaseItem> LoadChildren()
  510. {
  511. //just load our children from the repo - the library will be validated and maintained in other processes
  512. return GetCachedChildren();
  513. }
  514. /// <summary>
  515. /// Gets or sets the current validation cancellation token source.
  516. /// </summary>
  517. /// <value>The current validation cancellation token source.</value>
  518. private CancellationTokenSource CurrentValidationCancellationTokenSource { get; set; }
  519. /// <summary>
  520. /// Validates that the children of the folder still exist
  521. /// </summary>
  522. /// <param name="progress">The progress.</param>
  523. /// <param name="cancellationToken">The cancellation token.</param>
  524. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  525. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  526. /// <returns>Task.</returns>
  527. public async Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken, bool? recursive = null, bool forceRefreshMetadata = false)
  528. {
  529. cancellationToken.ThrowIfCancellationRequested();
  530. // Cancel the current validation, if any
  531. if (CurrentValidationCancellationTokenSource != null)
  532. {
  533. CurrentValidationCancellationTokenSource.Cancel();
  534. }
  535. // Create an inner cancellation token. This can cancel all validations from this level on down,
  536. // but nothing above this
  537. var innerCancellationTokenSource = new CancellationTokenSource();
  538. try
  539. {
  540. CurrentValidationCancellationTokenSource = innerCancellationTokenSource;
  541. var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(innerCancellationTokenSource.Token, cancellationToken);
  542. await ValidateChildrenInternal(progress, linkedCancellationTokenSource.Token, recursive, forceRefreshMetadata).ConfigureAwait(false);
  543. }
  544. catch (OperationCanceledException ex)
  545. {
  546. Logger.Info("ValidateChildren cancelled for " + Name);
  547. // If the outer cancelletion token in the cause for the cancellation, throw it
  548. if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken)
  549. {
  550. throw;
  551. }
  552. }
  553. finally
  554. {
  555. // Null out the token source
  556. if (CurrentValidationCancellationTokenSource == innerCancellationTokenSource)
  557. {
  558. CurrentValidationCancellationTokenSource = null;
  559. }
  560. innerCancellationTokenSource.Dispose();
  561. }
  562. }
  563. /// <summary>
  564. /// Compare our current children (presumably just read from the repo) with the current state of the file system and adjust for any changes
  565. /// ***Currently does not contain logic to maintain items that are unavailable in the file system***
  566. /// </summary>
  567. /// <param name="progress">The progress.</param>
  568. /// <param name="cancellationToken">The cancellation token.</param>
  569. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  570. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  571. /// <returns>Task.</returns>
  572. protected async virtual Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool? recursive = null, bool forceRefreshMetadata = false)
  573. {
  574. var locationType = LocationType;
  575. // Nothing to do here
  576. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  577. {
  578. return;
  579. }
  580. cancellationToken.ThrowIfCancellationRequested();
  581. IEnumerable<BaseItem> nonCachedChildren;
  582. try
  583. {
  584. nonCachedChildren = GetNonCachedChildren();
  585. }
  586. catch (IOException ex)
  587. {
  588. nonCachedChildren = new BaseItem[] { };
  589. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  590. }
  591. if (nonCachedChildren == null) return; //nothing to validate
  592. progress.Report(5);
  593. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  594. var currentChildren = ActualChildren.ToDictionary(i => i.Id);
  595. //create a list for our validated children
  596. var validChildren = new List<Tuple<BaseItem, bool>>();
  597. var newItems = new List<BaseItem>();
  598. cancellationToken.ThrowIfCancellationRequested();
  599. foreach (var child in nonCachedChildren)
  600. {
  601. BaseItem currentChild;
  602. if (currentChildren.TryGetValue(child.Id, out currentChild))
  603. {
  604. currentChild.ResetResolveArgs(child.ResolveArgs);
  605. //existing item - check if it has changed
  606. if (currentChild.HasChanged(child))
  607. {
  608. EntityResolutionHelper.EnsureDates(currentChild, child.ResolveArgs, false);
  609. validChildren.Add(new Tuple<BaseItem, bool>(currentChild, true));
  610. }
  611. else
  612. {
  613. validChildren.Add(new Tuple<BaseItem, bool>(currentChild, false));
  614. }
  615. currentChild.IsOffline = false;
  616. }
  617. else
  618. {
  619. //brand new item - needs to be added
  620. newItems.Add(child);
  621. validChildren.Add(new Tuple<BaseItem, bool>(child, true));
  622. }
  623. }
  624. // If any items were added or removed....
  625. if (newItems.Count > 0 || currentChildren.Count != validChildren.Count)
  626. {
  627. var newChildren = validChildren.Select(c => c.Item1).ToList();
  628. //that's all the new and changed ones - now see if there are any that are missing
  629. var itemsRemoved = currentChildren.Values.Except(newChildren).ToList();
  630. var actualRemovals = new List<BaseItem>();
  631. foreach (var item in itemsRemoved)
  632. {
  633. if (item.LocationType == LocationType.Virtual ||
  634. item.LocationType == LocationType.Remote)
  635. {
  636. // Don't remove these because there's no way to accurately validate them.
  637. continue;
  638. }
  639. if (!string.IsNullOrEmpty(item.Path) && IsPathOffline(item.Path))
  640. {
  641. item.IsOffline = true;
  642. validChildren.Add(new Tuple<BaseItem, bool>(item, false));
  643. }
  644. else
  645. {
  646. item.IsOffline = false;
  647. actualRemovals.Add(item);
  648. }
  649. }
  650. if (actualRemovals.Count > 0)
  651. {
  652. RemoveChildrenInternal(actualRemovals);
  653. foreach (var item in actualRemovals)
  654. {
  655. LibraryManager.ReportItemRemoved(item);
  656. }
  657. }
  658. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  659. AddChildrenInternal(newItems);
  660. await ItemRepository.SaveChildren(Id, _children.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  661. //force the indexes to rebuild next time
  662. if (IndexCache != null)
  663. {
  664. IndexCache.Clear();
  665. }
  666. }
  667. progress.Report(10);
  668. cancellationToken.ThrowIfCancellationRequested();
  669. await RefreshChildren(validChildren, progress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  670. progress.Report(100);
  671. }
  672. /// <summary>
  673. /// Refreshes the children.
  674. /// </summary>
  675. /// <param name="children">The children.</param>
  676. /// <param name="progress">The progress.</param>
  677. /// <param name="cancellationToken">The cancellation token.</param>
  678. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  679. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  680. /// <returns>Task.</returns>
  681. private async Task RefreshChildren(IList<Tuple<BaseItem, bool>> children, IProgress<double> progress, CancellationToken cancellationToken, bool? recursive, bool forceRefreshMetadata = false)
  682. {
  683. var list = children;
  684. var percentages = new Dictionary<Guid, double>(list.Count);
  685. var tasks = new List<Task>();
  686. foreach (var tuple in list)
  687. {
  688. if (tasks.Count > 5)
  689. {
  690. await Task.WhenAll(tasks).ConfigureAwait(false);
  691. }
  692. Tuple<BaseItem, bool> currentTuple = tuple;
  693. tasks.Add(Task.Run(async () =>
  694. {
  695. cancellationToken.ThrowIfCancellationRequested();
  696. var child = currentTuple.Item1;
  697. 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 (ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1148. {
  1149. return this;
  1150. }
  1151. }
  1152. catch (IOException ex)
  1153. {
  1154. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1155. }
  1156. //this should be functionally equivilent to what was here since it is IEnum and works on a thread-safe copy
  1157. return RecursiveChildren.FirstOrDefault(i =>
  1158. {
  1159. try
  1160. {
  1161. return i.ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase);
  1162. }
  1163. catch (IOException ex)
  1164. {
  1165. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1166. return false;
  1167. }
  1168. });
  1169. }
  1170. }
  1171. }