Folder.cs 45 KB

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