Folder.cs 39 KB

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