Folder.cs 39 KB

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