Folder.cs 35 KB

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