Folder.cs 33 KB

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