Folder.cs 39 KB

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