Folder.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  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. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  500. /// <returns>Task.</returns>
  501. public async Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken, bool? recursive = null, bool forceRefreshMetadata = false)
  502. {
  503. cancellationToken.ThrowIfCancellationRequested();
  504. // Cancel the current validation, if any
  505. if (CurrentValidationCancellationTokenSource != null)
  506. {
  507. CurrentValidationCancellationTokenSource.Cancel();
  508. }
  509. // Create an inner cancellation token. This can cancel all validations from this level on down,
  510. // but nothing above this
  511. var innerCancellationTokenSource = new CancellationTokenSource();
  512. try
  513. {
  514. CurrentValidationCancellationTokenSource = innerCancellationTokenSource;
  515. var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(innerCancellationTokenSource.Token, cancellationToken);
  516. await ValidateChildrenInternal(progress, linkedCancellationTokenSource.Token, recursive, forceRefreshMetadata).ConfigureAwait(false);
  517. }
  518. catch (OperationCanceledException ex)
  519. {
  520. Logger.Info("ValidateChildren cancelled for " + Name);
  521. // If the outer cancelletion token in the cause for the cancellation, throw it
  522. if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken)
  523. {
  524. throw;
  525. }
  526. }
  527. finally
  528. {
  529. // Null out the token source
  530. if (CurrentValidationCancellationTokenSource == innerCancellationTokenSource)
  531. {
  532. CurrentValidationCancellationTokenSource = null;
  533. }
  534. innerCancellationTokenSource.Dispose();
  535. }
  536. }
  537. /// <summary>
  538. /// Compare our current children (presumably just read from the repo) with the current state of the file system and adjust for any changes
  539. /// ***Currently does not contain logic to maintain items that are unavailable in the file system***
  540. /// </summary>
  541. /// <param name="progress">The progress.</param>
  542. /// <param name="cancellationToken">The cancellation token.</param>
  543. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  544. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  545. /// <returns>Task.</returns>
  546. protected async virtual Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool? recursive = null, bool forceRefreshMetadata = false)
  547. {
  548. // Nothing to do here
  549. if (LocationType != LocationType.FileSystem)
  550. {
  551. return;
  552. }
  553. cancellationToken.ThrowIfCancellationRequested();
  554. //get the current valid children from filesystem (or wherever)
  555. var nonCachedChildren = GetNonCachedChildren();
  556. if (nonCachedChildren == null) return; //nothing to validate
  557. progress.Report(5);
  558. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  559. var currentChildren = ActualChildren;
  560. //create a list for our validated children
  561. var validChildren = new ConcurrentBag<Tuple<BaseItem, bool>>();
  562. var newItems = new ConcurrentBag<BaseItem>();
  563. cancellationToken.ThrowIfCancellationRequested();
  564. var options = new ParallelOptions
  565. {
  566. MaxDegreeOfParallelism = 50
  567. };
  568. Parallel.ForEach(nonCachedChildren, options, child =>
  569. {
  570. BaseItem currentChild;
  571. if (currentChildren.TryGetValue(child.Id, out currentChild))
  572. {
  573. currentChild.ResolveArgs = child.ResolveArgs;
  574. //existing item - check if it has changed
  575. if (currentChild.HasChanged(child))
  576. {
  577. EntityResolutionHelper.EnsureDates(currentChild, child.ResolveArgs);
  578. validChildren.Add(new Tuple<BaseItem, bool>(currentChild, true));
  579. }
  580. else
  581. {
  582. validChildren.Add(new Tuple<BaseItem, bool>(currentChild, false));
  583. }
  584. }
  585. else
  586. {
  587. //brand new item - needs to be added
  588. newItems.Add(child);
  589. validChildren.Add(new Tuple<BaseItem, bool>(child, true));
  590. }
  591. });
  592. // If any items were added or removed....
  593. if (!newItems.IsEmpty || currentChildren.Count != validChildren.Count)
  594. {
  595. var newChildren = validChildren.Select(c => c.Item1).ToList();
  596. //that's all the new and changed ones - now see if there are any that are missing
  597. var itemsRemoved = currentChildren.Values.Except(newChildren).ToList();
  598. foreach (var item in itemsRemoved)
  599. {
  600. BaseItem removed;
  601. if (!_children.TryRemove(item.Id, out removed))
  602. {
  603. Logger.Error("Failed to remove {0}", item.Name);
  604. }
  605. else
  606. {
  607. LibraryManager.ReportItemRemoved(item);
  608. }
  609. }
  610. var saveTasks = new List<Task>();
  611. foreach (var item in newItems)
  612. {
  613. if (saveTasks.Count > 50)
  614. {
  615. await Task.WhenAll(saveTasks).ConfigureAwait(false);
  616. saveTasks.Clear();
  617. }
  618. if (!_children.TryAdd(item.Id, item))
  619. {
  620. Logger.Error("Failed to add {0}", item.Name);
  621. }
  622. else
  623. {
  624. Logger.Debug("** " + item.Name + " Added to library.");
  625. }
  626. saveTasks.Add(LibraryManager.CreateItem(item, CancellationToken.None));
  627. }
  628. await Task.WhenAll(saveTasks).ConfigureAwait(false);
  629. await LibraryManager.SaveChildren(Id, newChildren, CancellationToken.None).ConfigureAwait(false);
  630. //force the indexes to rebuild next time
  631. IndexCache.Clear();
  632. }
  633. progress.Report(10);
  634. cancellationToken.ThrowIfCancellationRequested();
  635. await RefreshChildren(validChildren, progress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  636. progress.Report(100);
  637. }
  638. /// <summary>
  639. /// Refreshes the children.
  640. /// </summary>
  641. /// <param name="children">The children.</param>
  642. /// <param name="progress">The progress.</param>
  643. /// <param name="cancellationToken">The cancellation token.</param>
  644. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  645. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  646. /// <returns>Task.</returns>
  647. private async Task RefreshChildren(IEnumerable<Tuple<BaseItem, bool>> children, IProgress<double> progress, CancellationToken cancellationToken, bool? recursive, bool forceRefreshMetadata = false)
  648. {
  649. var list = children.ToList();
  650. var percentages = new Dictionary<Guid, double>();
  651. var tasks = new List<Task>();
  652. foreach (var tuple in list)
  653. {
  654. if (tasks.Count > 8)
  655. {
  656. await Task.WhenAll(tasks).ConfigureAwait(false);
  657. }
  658. Tuple<BaseItem, bool> currentTuple = tuple;
  659. tasks.Add(Task.Run(async () =>
  660. {
  661. cancellationToken.ThrowIfCancellationRequested();
  662. var child = currentTuple.Item1;
  663. //refresh it
  664. await child.RefreshMetadata(cancellationToken, resetResolveArgs: child.IsFolder, forceSave: currentTuple.Item2, forceRefresh: forceRefreshMetadata).ConfigureAwait(false);
  665. // Refresh children if a folder and the item changed or recursive is set to true
  666. var refreshChildren = child.IsFolder && (currentTuple.Item2 || (recursive.HasValue && recursive.Value));
  667. if (refreshChildren)
  668. {
  669. // Don't refresh children if explicitly set to false
  670. if (recursive.HasValue && recursive.Value == false)
  671. {
  672. refreshChildren = false;
  673. }
  674. }
  675. if (refreshChildren)
  676. {
  677. cancellationToken.ThrowIfCancellationRequested();
  678. var innerProgress = new ActionableProgress<double>();
  679. innerProgress.RegisterAction(p =>
  680. {
  681. lock (percentages)
  682. {
  683. percentages[child.Id] = p/100;
  684. var percent = percentages.Values.Sum();
  685. percent /= list.Count;
  686. progress.Report((90 * percent) + 10);
  687. }
  688. });
  689. await ((Folder)child).ValidateChildren(innerProgress, cancellationToken, recursive).ConfigureAwait(false);
  690. }
  691. else
  692. {
  693. lock (percentages)
  694. {
  695. percentages[child.Id] = 1;
  696. var percent = percentages.Values.Sum();
  697. percent /= list.Count;
  698. progress.Report((90 * percent) + 10);
  699. }
  700. }
  701. }));
  702. }
  703. cancellationToken.ThrowIfCancellationRequested();
  704. await Task.WhenAll(tasks).ConfigureAwait(false);
  705. }
  706. /// <summary>
  707. /// Get the children of this folder from the actual file system
  708. /// </summary>
  709. /// <returns>IEnumerable{BaseItem}.</returns>
  710. protected virtual IEnumerable<BaseItem> GetNonCachedChildren()
  711. {
  712. IEnumerable<FileSystemInfo> fileSystemChildren;
  713. try
  714. {
  715. fileSystemChildren = ResolveArgs.FileSystemChildren;
  716. }
  717. catch (IOException ex)
  718. {
  719. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  720. return new List<BaseItem>();
  721. }
  722. return LibraryManager.ResolvePaths<BaseItem>(fileSystemChildren, this);
  723. }
  724. /// <summary>
  725. /// Get our children from the repo - stubbed for now
  726. /// </summary>
  727. /// <returns>IEnumerable{BaseItem}.</returns>
  728. protected virtual IEnumerable<BaseItem> GetCachedChildren()
  729. {
  730. return LibraryManager.RetrieveChildren(this).Select(i => i is IByReferenceItem ? LibraryManager.GetOrAddByReferenceItem(i) : i);
  731. }
  732. /// <summary>
  733. /// Gets allowed children of an item
  734. /// </summary>
  735. /// <param name="user">The user.</param>
  736. /// <param name="indexBy">The index by.</param>
  737. /// <returns>IEnumerable{BaseItem}.</returns>
  738. /// <exception cref="System.ArgumentNullException"></exception>
  739. public virtual IEnumerable<BaseItem> GetChildren(User user, string indexBy = null)
  740. {
  741. if (user == null)
  742. {
  743. throw new ArgumentNullException();
  744. }
  745. //the true root should return our users root folder children
  746. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, indexBy);
  747. IEnumerable<BaseItem> result = null;
  748. if (!string.IsNullOrEmpty(indexBy))
  749. {
  750. result = GetIndexedChildren(user, indexBy);
  751. }
  752. // If indexed is false or the indexing function is null
  753. return result ?? (Children.Where(c => c.IsVisible(user)));
  754. }
  755. /// <summary>
  756. /// Gets allowed recursive children of an item
  757. /// </summary>
  758. /// <param name="user">The user.</param>
  759. /// <returns>IEnumerable{BaseItem}.</returns>
  760. /// <exception cref="System.ArgumentNullException"></exception>
  761. public IEnumerable<BaseItem> GetRecursiveChildren(User user)
  762. {
  763. if (user == null)
  764. {
  765. throw new ArgumentNullException();
  766. }
  767. foreach (var item in GetChildren(user))
  768. {
  769. yield return item;
  770. var subFolder = item as Folder;
  771. if (subFolder != null)
  772. {
  773. foreach (var subitem in subFolder.GetRecursiveChildren(user))
  774. {
  775. yield return subitem;
  776. }
  777. }
  778. }
  779. }
  780. /// <summary>
  781. /// Folders need to validate and refresh
  782. /// </summary>
  783. /// <returns>Task.</returns>
  784. public override async Task ChangedExternally()
  785. {
  786. await base.ChangedExternally().ConfigureAwait(false);
  787. var progress = new Progress<double>();
  788. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  789. }
  790. /// <summary>
  791. /// Marks the item as either played or unplayed
  792. /// </summary>
  793. /// <param name="user">The user.</param>
  794. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  795. /// <param name="userManager">The user manager.</param>
  796. /// <returns>Task.</returns>
  797. public override async Task SetPlayedStatus(User user, bool wasPlayed, IUserDataRepository userManager)
  798. {
  799. // Sweep through recursively and update status
  800. var tasks = GetRecursiveChildren(user).Where(i => !i.IsFolder).Select(c => c.SetPlayedStatus(user, wasPlayed, userManager));
  801. await Task.WhenAll(tasks).ConfigureAwait(false);
  802. }
  803. /// <summary>
  804. /// Finds an item by path, recursively
  805. /// </summary>
  806. /// <param name="path">The path.</param>
  807. /// <returns>BaseItem.</returns>
  808. /// <exception cref="System.ArgumentNullException"></exception>
  809. public BaseItem FindByPath(string path)
  810. {
  811. if (string.IsNullOrEmpty(path))
  812. {
  813. throw new ArgumentNullException();
  814. }
  815. try
  816. {
  817. if (ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  818. {
  819. return this;
  820. }
  821. }
  822. catch (IOException ex)
  823. {
  824. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  825. }
  826. //this should be functionally equivilent to what was here since it is IEnum and works on a thread-safe copy
  827. return RecursiveChildren.FirstOrDefault(i =>
  828. {
  829. try
  830. {
  831. return i.ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase);
  832. }
  833. catch (IOException ex)
  834. {
  835. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  836. return false;
  837. }
  838. });
  839. }
  840. }
  841. }