Folder.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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. var options = new ParallelOptions
  483. {
  484. };
  485. Parallel.ForEach(nonCachedChildren, options, child =>
  486. {
  487. BaseItem currentChild;
  488. if (currentChildren.TryGetValue(child.Id, out currentChild))
  489. {
  490. currentChild.ResolveArgs = child.ResolveArgs;
  491. //existing item - check if it has changed
  492. if (currentChild.HasChanged(child))
  493. {
  494. EntityResolutionHelper.EnsureDates(currentChild, child.ResolveArgs);
  495. changedArgs.AddUpdatedItem(currentChild);
  496. validChildren.Add(new Tuple<BaseItem, bool>(currentChild, true));
  497. }
  498. else
  499. {
  500. validChildren.Add(new Tuple<BaseItem, bool>(currentChild, false));
  501. }
  502. }
  503. else
  504. {
  505. //brand new item - needs to be added
  506. changedArgs.AddNewItem(child);
  507. validChildren.Add(new Tuple<BaseItem, bool>(child, true));
  508. }
  509. });
  510. // If any items were added or removed....
  511. if (!changedArgs.ItemsAdded.IsEmpty || currentChildren.Count != validChildren.Count)
  512. {
  513. var newChildren = validChildren.Select(c => c.Item1).ToList();
  514. //that's all the new and changed ones - now see if there are any that are missing
  515. changedArgs.ItemsRemoved = currentChildren.Values.Except(newChildren).ToList();
  516. foreach (var item in changedArgs.ItemsRemoved)
  517. {
  518. Logger.Debug("** " + item.Name + " Removed from library.");
  519. }
  520. var childrenReplaced = false;
  521. if (changedArgs.ItemsRemoved.Count > 0)
  522. {
  523. ActualChildren = new ConcurrentBag<BaseItem>(newChildren);
  524. childrenReplaced = true;
  525. }
  526. var saveTasks = new List<Task>();
  527. foreach (var item in changedArgs.ItemsAdded)
  528. {
  529. Logger.Debug("** " + item.Name + " Added to library.");
  530. if (!childrenReplaced)
  531. {
  532. _children.Add(item);
  533. }
  534. saveTasks.Add(LibraryManager.SaveItem(item, CancellationToken.None));
  535. }
  536. await Task.WhenAll(saveTasks).ConfigureAwait(false);
  537. //and save children in repo...
  538. Logger.Debug("*** Saving " + newChildren.Count + " children for " + Name);
  539. await LibraryManager.SaveChildren(Id, newChildren, CancellationToken.None).ConfigureAwait(false);
  540. }
  541. if (changedArgs.HasChange)
  542. {
  543. //force the indexes to rebuild next time
  544. IndexCache.Clear();
  545. //and fire event
  546. LibraryManager.ReportLibraryChanged(changedArgs);
  547. }
  548. progress.Report(10);
  549. cancellationToken.ThrowIfCancellationRequested();
  550. await RefreshChildren(validChildren, progress, cancellationToken, recursive).ConfigureAwait(false);
  551. progress.Report(100);
  552. }
  553. /// <summary>
  554. /// Refreshes the children.
  555. /// </summary>
  556. /// <param name="children">The children.</param>
  557. /// <param name="progress">The progress.</param>
  558. /// <param name="cancellationToken">The cancellation token.</param>
  559. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  560. /// <returns>Task.</returns>
  561. private Task RefreshChildren(IEnumerable<Tuple<BaseItem, bool>> children, IProgress<double> progress, CancellationToken cancellationToken, bool? recursive)
  562. {
  563. var list = children.ToList();
  564. var percentages = new ConcurrentDictionary<Guid, double>(list.Select(i => new KeyValuePair<Guid, double>(i.Item1.Id, 0)));
  565. var tasks = list.Select(tuple => Task.Run(async () =>
  566. {
  567. cancellationToken.ThrowIfCancellationRequested();
  568. var child = tuple.Item1;
  569. //refresh it
  570. await child.RefreshMetadata(cancellationToken, resetResolveArgs: child.IsFolder).ConfigureAwait(false);
  571. // Refresh children if a folder and the item changed or recursive is set to true
  572. var refreshChildren = child.IsFolder && (tuple.Item2 || (recursive.HasValue && recursive.Value));
  573. if (refreshChildren)
  574. {
  575. // Don't refresh children if explicitly set to false
  576. if (recursive.HasValue && recursive.Value == false)
  577. {
  578. refreshChildren = false;
  579. }
  580. }
  581. if (refreshChildren)
  582. {
  583. cancellationToken.ThrowIfCancellationRequested();
  584. var innerProgress = new ActionableProgress<double>();
  585. innerProgress.RegisterAction(p =>
  586. {
  587. percentages.TryUpdate(child.Id, p / 100, percentages[child.Id]);
  588. var percent = percentages.Values.Sum();
  589. percent /= list.Count;
  590. progress.Report((90 * percent) + 10);
  591. });
  592. await ((Folder) child).ValidateChildren(innerProgress, cancellationToken, recursive).ConfigureAwait(false);
  593. }
  594. else
  595. {
  596. percentages.TryUpdate(child.Id, 1, percentages[child.Id]);
  597. var percent = percentages.Values.Sum();
  598. percent /= list.Count;
  599. progress.Report((90 * percent) + 10);
  600. }
  601. }));
  602. cancellationToken.ThrowIfCancellationRequested();
  603. return Task.WhenAll(tasks);
  604. }
  605. /// <summary>
  606. /// Get the children of this folder from the actual file system
  607. /// </summary>
  608. /// <returns>IEnumerable{BaseItem}.</returns>
  609. protected virtual IEnumerable<BaseItem> GetNonCachedChildren()
  610. {
  611. IEnumerable<WIN32_FIND_DATA> fileSystemChildren;
  612. try
  613. {
  614. fileSystemChildren = ResolveArgs.FileSystemChildren;
  615. }
  616. catch (IOException ex)
  617. {
  618. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  619. return new List<BaseItem>();
  620. }
  621. return LibraryManager.ResolvePaths<BaseItem>(fileSystemChildren, this);
  622. }
  623. /// <summary>
  624. /// Get our children from the repo - stubbed for now
  625. /// </summary>
  626. /// <returns>IEnumerable{BaseItem}.</returns>
  627. protected virtual IEnumerable<BaseItem> GetCachedChildren()
  628. {
  629. return LibraryManager.RetrieveChildren(this).Select(i => i is IByReferenceItem ? LibraryManager.GetOrAddByReferenceItem(i) : i);
  630. }
  631. /// <summary>
  632. /// Gets allowed children of an item
  633. /// </summary>
  634. /// <param name="user">The user.</param>
  635. /// <param name="indexBy">The index by.</param>
  636. /// <returns>IEnumerable{BaseItem}.</returns>
  637. /// <exception cref="System.ArgumentNullException"></exception>
  638. public virtual IEnumerable<BaseItem> GetChildren(User user, string indexBy = null)
  639. {
  640. if (user == null)
  641. {
  642. throw new ArgumentNullException();
  643. }
  644. //the true root should return our users root folder children
  645. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, indexBy);
  646. IEnumerable<BaseItem> result = null;
  647. if (!string.IsNullOrEmpty(indexBy))
  648. {
  649. result = GetIndexedChildren(user, indexBy);
  650. }
  651. // If indexed is false or the indexing function is null
  652. return result ?? (ActualChildren.Where(c => c.IsVisible(user)));
  653. }
  654. /// <summary>
  655. /// Gets allowed recursive children of an item
  656. /// </summary>
  657. /// <param name="user">The user.</param>
  658. /// <returns>IEnumerable{BaseItem}.</returns>
  659. /// <exception cref="System.ArgumentNullException"></exception>
  660. public IEnumerable<BaseItem> GetRecursiveChildren(User user)
  661. {
  662. if (user == null)
  663. {
  664. throw new ArgumentNullException();
  665. }
  666. foreach (var item in GetChildren(user))
  667. {
  668. yield return item;
  669. var subFolder = item as Folder;
  670. if (subFolder != null)
  671. {
  672. foreach (var subitem in subFolder.GetRecursiveChildren(user))
  673. {
  674. yield return subitem;
  675. }
  676. }
  677. }
  678. }
  679. /// <summary>
  680. /// Folders need to validate and refresh
  681. /// </summary>
  682. /// <returns>Task.</returns>
  683. public override async Task ChangedExternally()
  684. {
  685. await base.ChangedExternally().ConfigureAwait(false);
  686. var progress = new Progress<double>();
  687. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  688. }
  689. /// <summary>
  690. /// Marks the item as either played or unplayed
  691. /// </summary>
  692. /// <param name="user">The user.</param>
  693. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  694. /// <param name="userManager">The user manager.</param>
  695. /// <returns>Task.</returns>
  696. public override async Task SetPlayedStatus(User user, bool wasPlayed, IUserManager userManager)
  697. {
  698. await base.SetPlayedStatus(user, wasPlayed, userManager).ConfigureAwait(false);
  699. // Now sweep through recursively and update status
  700. var tasks = GetChildren(user).Select(c => c.SetPlayedStatus(user, wasPlayed, userManager));
  701. await Task.WhenAll(tasks).ConfigureAwait(false);
  702. }
  703. /// <summary>
  704. /// Finds an item by path, recursively
  705. /// </summary>
  706. /// <param name="path">The path.</param>
  707. /// <returns>BaseItem.</returns>
  708. /// <exception cref="System.ArgumentNullException"></exception>
  709. public BaseItem FindByPath(string path)
  710. {
  711. if (string.IsNullOrEmpty(path))
  712. {
  713. throw new ArgumentNullException();
  714. }
  715. try
  716. {
  717. if (ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  718. {
  719. return this;
  720. }
  721. }
  722. catch (IOException ex)
  723. {
  724. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  725. }
  726. //this should be functionally equivilent to what was here since it is IEnum and works on a thread-safe copy
  727. return RecursiveChildren.FirstOrDefault(i =>
  728. {
  729. try
  730. {
  731. return i.ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase);
  732. }
  733. catch (IOException ex)
  734. {
  735. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  736. return false;
  737. }
  738. });
  739. }
  740. }
  741. }