Folder.cs 47 KB

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