Folder.cs 37 KB

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