Folder.cs 34 KB

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