Folder.cs 38 KB

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