Folder.cs 37 KB

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