Folder.cs 37 KB

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