Folder.cs 33 KB

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