Folder.cs 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  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.Resolvers;
  8. using MediaBrowser.Model.Entities;
  9. using System;
  10. using System.Collections;
  11. using System.Collections.Concurrent;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Runtime.Serialization;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Controller.Entities
  19. {
  20. /// <summary>
  21. /// Class Folder
  22. /// </summary>
  23. public class Folder : BaseItem
  24. {
  25. public Folder()
  26. {
  27. LinkedChildren = new List<LinkedChild>();
  28. }
  29. /// <summary>
  30. /// Gets a value indicating whether this instance is folder.
  31. /// </summary>
  32. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  33. [IgnoreDataMember]
  34. public override bool IsFolder
  35. {
  36. get
  37. {
  38. return true;
  39. }
  40. }
  41. /// <summary>
  42. /// Gets or sets a value indicating whether this instance is physical root.
  43. /// </summary>
  44. /// <value><c>true</c> if this instance is physical root; otherwise, <c>false</c>.</value>
  45. public bool IsPhysicalRoot { get; set; }
  46. /// <summary>
  47. /// Gets or sets a value indicating whether this instance is root.
  48. /// </summary>
  49. /// <value><c>true</c> if this instance is root; otherwise, <c>false</c>.</value>
  50. public bool IsRoot { get; set; }
  51. /// <summary>
  52. /// Gets a value indicating whether this instance is virtual folder.
  53. /// </summary>
  54. /// <value><c>true</c> if this instance is virtual folder; otherwise, <c>false</c>.</value>
  55. [IgnoreDataMember]
  56. public virtual bool IsVirtualFolder
  57. {
  58. get
  59. {
  60. return false;
  61. }
  62. }
  63. public virtual List<LinkedChild> LinkedChildren { get; set; }
  64. protected virtual bool SupportsShortcutChildren
  65. {
  66. get { return true; }
  67. }
  68. /// <summary>
  69. /// Adds the child.
  70. /// </summary>
  71. /// <param name="item">The item.</param>
  72. /// <param name="cancellationToken">The cancellation token.</param>
  73. /// <returns>Task.</returns>
  74. /// <exception cref="System.InvalidOperationException">Unable to add + item.Name</exception>
  75. public async Task AddChild(BaseItem item, CancellationToken cancellationToken)
  76. {
  77. item.Parent = this;
  78. if (item.Id == Guid.Empty)
  79. {
  80. item.Id = item.Path.GetMBId(item.GetType());
  81. }
  82. if (item.DateCreated == DateTime.MinValue)
  83. {
  84. item.DateCreated = DateTime.UtcNow;
  85. }
  86. if (item.DateModified == DateTime.MinValue)
  87. {
  88. item.DateModified = DateTime.UtcNow;
  89. }
  90. AddChildInternal(item);
  91. await LibraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  92. await ItemRepository.SaveChildren(Id, _children.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  93. }
  94. protected void AddChildrenInternal(IEnumerable<BaseItem> children)
  95. {
  96. lock (_childrenSyncLock)
  97. {
  98. var newChildren = _children.ToList();
  99. newChildren.AddRange(children);
  100. _children = newChildren;
  101. }
  102. }
  103. protected void AddChildInternal(BaseItem child)
  104. {
  105. lock (_childrenSyncLock)
  106. {
  107. var newChildren = _children.ToList();
  108. newChildren.Add(child);
  109. _children = newChildren;
  110. }
  111. }
  112. protected void RemoveChildrenInternal(IEnumerable<BaseItem> children)
  113. {
  114. lock (_childrenSyncLock)
  115. {
  116. _children = _children.Except(children).ToList();
  117. }
  118. }
  119. protected void ClearChildrenInternal()
  120. {
  121. lock (_childrenSyncLock)
  122. {
  123. _children = new List<BaseItem>();
  124. }
  125. }
  126. /// <summary>
  127. /// Never want folders to be blocked by "BlockNotRated"
  128. /// </summary>
  129. [IgnoreDataMember]
  130. public override string OfficialRatingForComparison
  131. {
  132. get
  133. {
  134. if (this is Series)
  135. {
  136. return base.OfficialRatingForComparison;
  137. }
  138. return !string.IsNullOrEmpty(base.OfficialRatingForComparison) ? base.OfficialRatingForComparison : "None";
  139. }
  140. }
  141. /// <summary>
  142. /// Removes the child.
  143. /// </summary>
  144. /// <param name="item">The item.</param>
  145. /// <param name="cancellationToken">The cancellation token.</param>
  146. /// <returns>Task.</returns>
  147. /// <exception cref="System.InvalidOperationException">Unable to remove + item.Name</exception>
  148. public Task RemoveChild(BaseItem item, CancellationToken cancellationToken)
  149. {
  150. RemoveChildrenInternal(new[] { item });
  151. item.Parent = null;
  152. LibraryManager.ReportItemRemoved(item);
  153. return ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken);
  154. }
  155. /// <summary>
  156. /// Clears the children.
  157. /// </summary>
  158. /// <param name="cancellationToken">The cancellation token.</param>
  159. /// <returns>Task.</returns>
  160. public Task ClearChildren(CancellationToken cancellationToken)
  161. {
  162. var items = ActualChildren.ToList();
  163. ClearChildrenInternal();
  164. foreach (var item in items)
  165. {
  166. LibraryManager.ReportItemRemoved(item);
  167. }
  168. return ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken);
  169. }
  170. #region Indexing
  171. /// <summary>
  172. /// The _index by options
  173. /// </summary>
  174. private Dictionary<string, Func<User, IEnumerable<BaseItem>>> _indexByOptions;
  175. /// <summary>
  176. /// Dictionary of index options - consists of a display value and an indexing function
  177. /// which takes User as a parameter and returns an IEnum of BaseItem
  178. /// </summary>
  179. /// <value>The index by options.</value>
  180. [IgnoreDataMember]
  181. public Dictionary<string, Func<User, IEnumerable<BaseItem>>> IndexByOptions
  182. {
  183. get { return _indexByOptions ?? (_indexByOptions = GetIndexByOptions()); }
  184. }
  185. /// <summary>
  186. /// Returns the valid set of index by options for this folder type.
  187. /// Override or extend to modify.
  188. /// </summary>
  189. /// <returns>Dictionary{System.StringFunc{UserIEnumerable{BaseItem}}}.</returns>
  190. protected virtual Dictionary<string, Func<User, IEnumerable<BaseItem>>> GetIndexByOptions()
  191. {
  192. return new Dictionary<string, Func<User, IEnumerable<BaseItem>>> {
  193. {LocalizedStrings.Instance.GetString("NoneDispPref"), null},
  194. {LocalizedStrings.Instance.GetString("PerformerDispPref"), GetIndexByPerformer},
  195. {LocalizedStrings.Instance.GetString("GenreDispPref"), GetIndexByGenre},
  196. {LocalizedStrings.Instance.GetString("DirectorDispPref"), GetIndexByDirector},
  197. {LocalizedStrings.Instance.GetString("YearDispPref"), GetIndexByYear},
  198. //{LocalizedStrings.Instance.GetString("OfficialRatingDispPref"), null},
  199. {LocalizedStrings.Instance.GetString("StudioDispPref"), GetIndexByStudio}
  200. };
  201. }
  202. /// <summary>
  203. /// Gets the index by actor.
  204. /// </summary>
  205. /// <param name="user">The user.</param>
  206. /// <returns>IEnumerable{BaseItem}.</returns>
  207. protected IEnumerable<BaseItem> GetIndexByPerformer(User user)
  208. {
  209. return GetIndexByPerson(user, new List<string> { PersonType.Actor, PersonType.GuestStar }, true, LocalizedStrings.Instance.GetString("PerformerDispPref"));
  210. }
  211. /// <summary>
  212. /// Gets the index by director.
  213. /// </summary>
  214. /// <param name="user">The user.</param>
  215. /// <returns>IEnumerable{BaseItem}.</returns>
  216. protected IEnumerable<BaseItem> GetIndexByDirector(User user)
  217. {
  218. return GetIndexByPerson(user, new List<string> { PersonType.Director }, false, LocalizedStrings.Instance.GetString("DirectorDispPref"));
  219. }
  220. /// <summary>
  221. /// Gets the index by person.
  222. /// </summary>
  223. /// <param name="user">The user.</param>
  224. /// <param name="personTypes">The person types we should match on</param>
  225. /// <param name="includeAudio">if set to <c>true</c> [include audio].</param>
  226. /// <param name="indexName">Name of the index.</param>
  227. /// <returns>IEnumerable{BaseItem}.</returns>
  228. private IEnumerable<BaseItem> GetIndexByPerson(User user, List<string> personTypes, bool includeAudio, string indexName)
  229. {
  230. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  231. // the retrieval of the individual children for each index value until they are requested.
  232. using (new Profiler(indexName + " Index Build for " + Name, Logger))
  233. {
  234. // Put this in a local variable to avoid an implicitly captured closure
  235. var currentIndexName = indexName;
  236. var us = this;
  237. var recursiveChildren = GetRecursiveChildren(user).Where(i => i.IncludeInIndex).ToList();
  238. // Get the candidates, but handle audio separately
  239. var candidates = recursiveChildren.Where(i => i.AllPeople != null && !(i is Audio.Audio)).ToList();
  240. var indexFolders = candidates.AsParallel().SelectMany(i => i.AllPeople.Where(p => personTypes.Contains(p.Type))
  241. .Select(a => a.Name))
  242. .Distinct()
  243. .Select(i =>
  244. {
  245. try
  246. {
  247. return LibraryManager.GetPerson(i);
  248. }
  249. catch (IOException ex)
  250. {
  251. Logger.ErrorException("Error getting person {0}", ex, i);
  252. return null;
  253. }
  254. catch (AggregateException ex)
  255. {
  256. Logger.ErrorException("Error getting person {0}", ex, i);
  257. return null;
  258. }
  259. })
  260. .Where(i => i != null)
  261. .Select(a => new IndexFolder(us, a,
  262. candidates.Where(i => i.AllPeople.Any(p => personTypes.Contains(p.Type) && p.Name.Equals(a.Name, StringComparison.OrdinalIgnoreCase))
  263. ), currentIndexName)).AsEnumerable();
  264. if (includeAudio)
  265. {
  266. var songs = recursiveChildren.OfType<Audio.Audio>().ToList();
  267. indexFolders = songs.SelectMany(i => i.Artists)
  268. .Distinct(StringComparer.OrdinalIgnoreCase)
  269. .Select(i =>
  270. {
  271. try
  272. {
  273. return LibraryManager.GetArtist(i);
  274. }
  275. catch (IOException ex)
  276. {
  277. Logger.ErrorException("Error getting artist {0}", ex, i);
  278. return null;
  279. }
  280. catch (AggregateException ex)
  281. {
  282. Logger.ErrorException("Error getting artist {0}", ex, i);
  283. return null;
  284. }
  285. })
  286. .Where(i => i != null)
  287. .Select(a => new IndexFolder(us, a,
  288. songs.Where(i => i.Artists.Contains(a.Name, StringComparer.OrdinalIgnoreCase)
  289. ), currentIndexName)).Concat(indexFolders);
  290. }
  291. return indexFolders;
  292. }
  293. }
  294. /// <summary>
  295. /// Gets the index by studio.
  296. /// </summary>
  297. /// <param name="user">The user.</param>
  298. /// <returns>IEnumerable{BaseItem}.</returns>
  299. protected IEnumerable<BaseItem> GetIndexByStudio(User user)
  300. {
  301. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  302. // the retrieval of the individual children for each index value until they are requested.
  303. using (new Profiler("Studio Index Build for " + Name, Logger))
  304. {
  305. var indexName = LocalizedStrings.Instance.GetString("StudioDispPref");
  306. var candidates = GetRecursiveChildren(user).Where(i => i.IncludeInIndex).ToList();
  307. return candidates.AsParallel().SelectMany(i => i.AllStudios)
  308. .Distinct()
  309. .Select(i =>
  310. {
  311. try
  312. {
  313. return LibraryManager.GetStudio(i);
  314. }
  315. catch (IOException ex)
  316. {
  317. Logger.ErrorException("Error getting studio {0}", ex, i);
  318. return null;
  319. }
  320. catch (AggregateException ex)
  321. {
  322. Logger.ErrorException("Error getting studio {0}", ex, i);
  323. return null;
  324. }
  325. })
  326. .Where(i => i != null)
  327. .Select(ndx => new IndexFolder(this, ndx, candidates.Where(i => i.AllStudios.Any(s => s.Equals(ndx.Name, StringComparison.OrdinalIgnoreCase))), indexName));
  328. }
  329. }
  330. /// <summary>
  331. /// Gets the index by genre.
  332. /// </summary>
  333. /// <param name="user">The user.</param>
  334. /// <returns>IEnumerable{BaseItem}.</returns>
  335. protected IEnumerable<BaseItem> GetIndexByGenre(User user)
  336. {
  337. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  338. // the retrieval of the individual children for each index value until they are requested.
  339. using (new Profiler("Genre Index Build for " + Name, Logger))
  340. {
  341. var indexName = LocalizedStrings.Instance.GetString("GenreDispPref");
  342. //we need a copy of this so we don't double-recurse
  343. var candidates = GetRecursiveChildren(user).Where(i => i.IncludeInIndex).ToList();
  344. return candidates.AsParallel().SelectMany(i => i.AllGenres)
  345. .Distinct(StringComparer.OrdinalIgnoreCase)
  346. .Select(i =>
  347. {
  348. try
  349. {
  350. return LibraryManager.GetGenre(i);
  351. }
  352. catch (Exception ex)
  353. {
  354. Logger.ErrorException("Error getting genre {0}", ex, i);
  355. return null;
  356. }
  357. })
  358. .Where(i => i != null)
  359. .Select(genre => new IndexFolder(this, genre, candidates.Where(i => i.AllGenres.Any(g => g.Equals(genre.Name, StringComparison.OrdinalIgnoreCase))), indexName)
  360. );
  361. }
  362. }
  363. /// <summary>
  364. /// Gets the index by year.
  365. /// </summary>
  366. /// <param name="user">The user.</param>
  367. /// <returns>IEnumerable{BaseItem}.</returns>
  368. protected IEnumerable<BaseItem> GetIndexByYear(User user)
  369. {
  370. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  371. // the retrieval of the individual children for each index value until they are requested.
  372. using (new Profiler("Production Year Index Build for " + Name, Logger))
  373. {
  374. var indexName = LocalizedStrings.Instance.GetString("YearDispPref");
  375. //we need a copy of this so we don't double-recurse
  376. var candidates = GetRecursiveChildren(user).Where(i => i.IncludeInIndex && i.ProductionYear.HasValue).ToList();
  377. return candidates.AsParallel().Select(i => i.ProductionYear.Value)
  378. .Distinct()
  379. .Select(i =>
  380. {
  381. try
  382. {
  383. return LibraryManager.GetYear(i);
  384. }
  385. catch (IOException ex)
  386. {
  387. Logger.ErrorException("Error getting year {0}", ex, i);
  388. return null;
  389. }
  390. catch (AggregateException ex)
  391. {
  392. Logger.ErrorException("Error getting year {0}", ex, i);
  393. return null;
  394. }
  395. })
  396. .Where(i => i != null)
  397. .Select(ndx => new IndexFolder(this, ndx, candidates.Where(i => i.ProductionYear == int.Parse(ndx.Name)), indexName));
  398. }
  399. }
  400. /// <summary>
  401. /// Returns the indexed children for this user from the cache. Caches them if not already there.
  402. /// </summary>
  403. /// <param name="user">The user.</param>
  404. /// <param name="indexBy">The index by.</param>
  405. /// <returns>IEnumerable{BaseItem}.</returns>
  406. private IEnumerable<BaseItem> GetIndexedChildren(User user, string indexBy)
  407. {
  408. List<BaseItem> result = null;
  409. var cacheKey = user.Name + indexBy;
  410. if (IndexCache != null)
  411. {
  412. IndexCache.TryGetValue(cacheKey, out result);
  413. }
  414. if (result == null)
  415. {
  416. //not cached - cache it
  417. Func<User, IEnumerable<BaseItem>> indexing;
  418. IndexByOptions.TryGetValue(indexBy, out indexing);
  419. result = BuildIndex(indexBy, indexing, user);
  420. }
  421. return result;
  422. }
  423. /// <summary>
  424. /// Get the list of indexy by choices for this folder (localized).
  425. /// </summary>
  426. /// <value>The index by option strings.</value>
  427. [IgnoreDataMember]
  428. public IEnumerable<string> IndexByOptionStrings
  429. {
  430. get { return IndexByOptions.Keys; }
  431. }
  432. /// <summary>
  433. /// The index cache
  434. /// </summary>
  435. protected ConcurrentDictionary<string, List<BaseItem>> IndexCache;
  436. /// <summary>
  437. /// Builds the index.
  438. /// </summary>
  439. /// <param name="indexKey">The index key.</param>
  440. /// <param name="indexFunction">The index function.</param>
  441. /// <param name="user">The user.</param>
  442. /// <returns>List{BaseItem}.</returns>
  443. protected virtual List<BaseItem> BuildIndex(string indexKey, Func<User, IEnumerable<BaseItem>> indexFunction, User user)
  444. {
  445. if (IndexCache == null)
  446. {
  447. IndexCache = new ConcurrentDictionary<string, List<BaseItem>>();
  448. }
  449. return indexFunction != null
  450. ? IndexCache[user.Name + indexKey] = indexFunction(user).ToList()
  451. : null;
  452. }
  453. #endregion
  454. /// <summary>
  455. /// The children
  456. /// </summary>
  457. private IReadOnlyList<BaseItem> _children = new List<BaseItem>();
  458. /// <summary>
  459. /// The _children sync lock
  460. /// </summary>
  461. private readonly object _childrenSyncLock = new object();
  462. /// <summary>
  463. /// Gets or sets the actual children.
  464. /// </summary>
  465. /// <value>The actual children.</value>
  466. protected virtual IEnumerable<BaseItem> ActualChildren
  467. {
  468. get
  469. {
  470. return _children;
  471. }
  472. }
  473. public void LoadSavedChildren()
  474. {
  475. _children = LoadChildrenInternal();
  476. }
  477. /// <summary>
  478. /// thread-safe access to the actual children of this folder - without regard to user
  479. /// </summary>
  480. /// <value>The children.</value>
  481. [IgnoreDataMember]
  482. public IEnumerable<BaseItem> Children
  483. {
  484. get { return ActualChildren; }
  485. }
  486. /// <summary>
  487. /// thread-safe access to all recursive children of this folder - without regard to user
  488. /// </summary>
  489. /// <value>The recursive children.</value>
  490. [IgnoreDataMember]
  491. public IEnumerable<BaseItem> RecursiveChildren
  492. {
  493. get { return GetRecursiveChildren(); }
  494. }
  495. private List<BaseItem> LoadChildrenInternal()
  496. {
  497. return LoadChildren().ToList();
  498. }
  499. /// <summary>
  500. /// Loads our children. Validation will occur externally.
  501. /// We want this sychronous.
  502. /// </summary>
  503. protected virtual IEnumerable<BaseItem> LoadChildren()
  504. {
  505. //just load our children from the repo - the library will be validated and maintained in other processes
  506. return GetCachedChildren();
  507. }
  508. /// <summary>
  509. /// Gets or sets the current validation cancellation token source.
  510. /// </summary>
  511. /// <value>The current validation cancellation token source.</value>
  512. private CancellationTokenSource CurrentValidationCancellationTokenSource { get; set; }
  513. /// <summary>
  514. /// Validates that the children of the folder still exist
  515. /// </summary>
  516. /// <param name="progress">The progress.</param>
  517. /// <param name="cancellationToken">The cancellation token.</param>
  518. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  519. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  520. /// <returns>Task.</returns>
  521. public async Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken, bool? recursive = null, bool forceRefreshMetadata = false)
  522. {
  523. cancellationToken.ThrowIfCancellationRequested();
  524. // Cancel the current validation, if any
  525. if (CurrentValidationCancellationTokenSource != null)
  526. {
  527. CurrentValidationCancellationTokenSource.Cancel();
  528. }
  529. // Create an inner cancellation token. This can cancel all validations from this level on down,
  530. // but nothing above this
  531. var innerCancellationTokenSource = new CancellationTokenSource();
  532. try
  533. {
  534. CurrentValidationCancellationTokenSource = innerCancellationTokenSource;
  535. var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(innerCancellationTokenSource.Token, cancellationToken);
  536. await ValidateChildrenInternal(progress, linkedCancellationTokenSource.Token, recursive, forceRefreshMetadata).ConfigureAwait(false);
  537. }
  538. catch (OperationCanceledException ex)
  539. {
  540. Logger.Info("ValidateChildren cancelled for " + Name);
  541. // If the outer cancelletion token in the cause for the cancellation, throw it
  542. if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken)
  543. {
  544. throw;
  545. }
  546. }
  547. finally
  548. {
  549. // Null out the token source
  550. if (CurrentValidationCancellationTokenSource == innerCancellationTokenSource)
  551. {
  552. CurrentValidationCancellationTokenSource = null;
  553. }
  554. innerCancellationTokenSource.Dispose();
  555. }
  556. }
  557. /// <summary>
  558. /// Compare our current children (presumably just read from the repo) with the current state of the file system and adjust for any changes
  559. /// ***Currently does not contain logic to maintain items that are unavailable in the file system***
  560. /// </summary>
  561. /// <param name="progress">The progress.</param>
  562. /// <param name="cancellationToken">The cancellation token.</param>
  563. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  564. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  565. /// <returns>Task.</returns>
  566. protected async virtual Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool? recursive = null, bool forceRefreshMetadata = false)
  567. {
  568. var locationType = LocationType;
  569. // Nothing to do here
  570. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  571. {
  572. return;
  573. }
  574. cancellationToken.ThrowIfCancellationRequested();
  575. IEnumerable<BaseItem> nonCachedChildren;
  576. try
  577. {
  578. nonCachedChildren = GetNonCachedChildren();
  579. }
  580. catch (IOException ex)
  581. {
  582. nonCachedChildren = new BaseItem[] { };
  583. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  584. }
  585. if (nonCachedChildren == null) return; //nothing to validate
  586. progress.Report(5);
  587. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  588. var currentChildren = ActualChildren.ToDictionary(i => i.Id);
  589. //create a list for our validated children
  590. var validChildren = new List<Tuple<BaseItem, bool>>();
  591. var newItems = new List<BaseItem>();
  592. cancellationToken.ThrowIfCancellationRequested();
  593. foreach (var child in nonCachedChildren)
  594. {
  595. BaseItem currentChild;
  596. if (currentChildren.TryGetValue(child.Id, out currentChild))
  597. {
  598. currentChild.ResetResolveArgs(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.Count > 0 || 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. foreach (var item in actualRemovals)
  642. {
  643. LibraryManager.ReportItemRemoved(item);
  644. }
  645. }
  646. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  647. AddChildrenInternal(newItems);
  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(IList<Tuple<BaseItem, bool>> children, IProgress<double> progress, CancellationToken cancellationToken, bool? recursive, bool forceRefreshMetadata = false)
  670. {
  671. var list = children;
  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 > 5)
  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. var initialCount = _children.Count;
  816. var list = new List<BaseItem>(initialCount);
  817. AddChildrenToList(user, includeLinkedChildren, list, false, null);
  818. return list;
  819. }
  820. /// <summary>
  821. /// Adds the children to list.
  822. /// </summary>
  823. /// <param name="user">The user.</param>
  824. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  825. /// <param name="list">The list.</param>
  826. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  827. /// <param name="filter">The filter.</param>
  828. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  829. private bool AddChildrenToList(User user, bool includeLinkedChildren, List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  830. {
  831. var hasLinkedChildren = false;
  832. foreach (var child in Children)
  833. {
  834. if (child.IsVisible(user))
  835. {
  836. if (filter == null || filter(child))
  837. {
  838. list.Add(child);
  839. }
  840. }
  841. if (recursive)
  842. {
  843. var folder = child as Folder;
  844. if (folder != null)
  845. {
  846. if (folder.AddChildrenToList(user, includeLinkedChildren, list, true, filter))
  847. {
  848. hasLinkedChildren = true;
  849. }
  850. }
  851. }
  852. }
  853. if (includeLinkedChildren)
  854. {
  855. foreach (var child in GetLinkedChildren())
  856. {
  857. if (filter != null && !filter(child))
  858. {
  859. continue;
  860. }
  861. hasLinkedChildren = true;
  862. if (child.IsVisible(user))
  863. {
  864. list.Add(child);
  865. }
  866. }
  867. }
  868. return hasLinkedChildren;
  869. }
  870. private int _lastRecursiveCount;
  871. /// <summary>
  872. /// Gets allowed recursive children of an item
  873. /// </summary>
  874. /// <param name="user">The user.</param>
  875. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  876. /// <returns>IEnumerable{BaseItem}.</returns>
  877. /// <exception cref="System.ArgumentNullException"></exception>
  878. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  879. {
  880. return GetRecursiveChildren(user, null, true);
  881. }
  882. /// <summary>
  883. /// Gets the recursive children.
  884. /// </summary>
  885. /// <param name="user">The user.</param>
  886. /// <param name="filter">The filter.</param>
  887. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  888. /// <returns>IList{BaseItem}.</returns>
  889. /// <exception cref="System.ArgumentNullException"></exception>
  890. public IList<BaseItem> GetRecursiveChildren(User user, Func<BaseItem, bool> filter, bool includeLinkedChildren = true)
  891. {
  892. if (user == null)
  893. {
  894. throw new ArgumentNullException();
  895. }
  896. var initialCount = _lastRecursiveCount == 0 ? _children.Count : _lastRecursiveCount;
  897. var list = new List<BaseItem>(initialCount);
  898. var hasLinkedChildren = AddChildrenToList(user, includeLinkedChildren, list, true, filter);
  899. _lastRecursiveCount = list.Count;
  900. if (includeLinkedChildren && hasLinkedChildren)
  901. {
  902. list = list.Distinct().ToList();
  903. }
  904. return list;
  905. }
  906. /// <summary>
  907. /// Gets the recursive children.
  908. /// </summary>
  909. /// <returns>IList{BaseItem}.</returns>
  910. public IList<BaseItem> GetRecursiveChildren()
  911. {
  912. return GetRecursiveChildren(null);
  913. }
  914. /// <summary>
  915. /// Gets the recursive children.
  916. /// </summary>
  917. /// <param name="filter">The filter.</param>
  918. /// <returns>IEnumerable{BaseItem}.</returns>
  919. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  920. {
  921. var initialCount = _lastRecursiveCount == 0 ? _children.Count : _lastRecursiveCount;
  922. var list = new List<BaseItem>(initialCount);
  923. AddChildrenToList(list, true, filter);
  924. return list;
  925. }
  926. /// <summary>
  927. /// Adds the children to list.
  928. /// </summary>
  929. /// <param name="list">The list.</param>
  930. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  931. /// <param name="filter">The filter.</param>
  932. private void AddChildrenToList(List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  933. {
  934. foreach (var child in Children)
  935. {
  936. if (filter == null || filter(child))
  937. {
  938. list.Add(child);
  939. }
  940. if (recursive)
  941. {
  942. var folder = child as Folder;
  943. if (folder != null)
  944. {
  945. folder.AddChildrenToList(list, true, filter);
  946. }
  947. }
  948. }
  949. }
  950. /// <summary>
  951. /// Gets the linked children.
  952. /// </summary>
  953. /// <returns>IEnumerable{BaseItem}.</returns>
  954. public IEnumerable<BaseItem> GetLinkedChildren()
  955. {
  956. return LinkedChildren
  957. .Select(GetLinkedChild)
  958. .Where(i => i != null);
  959. }
  960. /// <summary>
  961. /// Gets the linked child.
  962. /// </summary>
  963. /// <param name="info">The info.</param>
  964. /// <returns>BaseItem.</returns>
  965. private BaseItem GetLinkedChild(LinkedChild info)
  966. {
  967. if (string.IsNullOrEmpty(info.Path))
  968. {
  969. throw new ArgumentException("Encountered linked child with empty path.");
  970. }
  971. BaseItem item = null;
  972. // First get using the cached Id
  973. if (info.ItemId != Guid.Empty)
  974. {
  975. item = LibraryManager.GetItemById(info.ItemId);
  976. }
  977. // If still null, search by path
  978. if (item == null)
  979. {
  980. item = LibraryManager.RootFolder.FindByPath(info.Path);
  981. }
  982. // If still null, log
  983. if (item == null)
  984. {
  985. Logger.Warn("Unable to find linked item at {0}", info.Path);
  986. }
  987. else
  988. {
  989. // Cache the id for next time
  990. info.ItemId = item.Id;
  991. }
  992. return item;
  993. }
  994. public override async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  995. {
  996. var changed = await base.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs).ConfigureAwait(false);
  997. return changed || (SupportsShortcutChildren && LocationType == LocationType.FileSystem && RefreshLinkedChildren());
  998. }
  999. /// <summary>
  1000. /// Refreshes the linked children.
  1001. /// </summary>
  1002. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1003. private bool RefreshLinkedChildren()
  1004. {
  1005. ItemResolveArgs resolveArgs;
  1006. try
  1007. {
  1008. resolveArgs = ResolveArgs;
  1009. if (!resolveArgs.IsDirectory)
  1010. {
  1011. return false;
  1012. }
  1013. }
  1014. catch (IOException ex)
  1015. {
  1016. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1017. return false;
  1018. }
  1019. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  1020. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1021. var newShortcutLinks = resolveArgs.FileSystemChildren
  1022. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  1023. .Select(i =>
  1024. {
  1025. try
  1026. {
  1027. Logger.Debug("Found shortcut at {0}", i.FullName);
  1028. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  1029. if (!string.IsNullOrEmpty(resolvedPath))
  1030. {
  1031. return new LinkedChild
  1032. {
  1033. Path = resolvedPath,
  1034. Type = LinkedChildType.Shortcut
  1035. };
  1036. }
  1037. Logger.Error("Error resolving shortcut {0}", i.FullName);
  1038. return null;
  1039. }
  1040. catch (IOException ex)
  1041. {
  1042. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  1043. return null;
  1044. }
  1045. })
  1046. .Where(i => i != null)
  1047. .ToList();
  1048. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  1049. {
  1050. Logger.Info("Shortcut links have changed for {0}", Path);
  1051. newShortcutLinks.AddRange(currentManualLinks);
  1052. LinkedChildren = newShortcutLinks;
  1053. return true;
  1054. }
  1055. return false;
  1056. }
  1057. /// <summary>
  1058. /// Folders need to validate and refresh
  1059. /// </summary>
  1060. /// <returns>Task.</returns>
  1061. public override async Task ChangedExternally()
  1062. {
  1063. await base.ChangedExternally().ConfigureAwait(false);
  1064. var progress = new Progress<double>();
  1065. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  1066. }
  1067. /// <summary>
  1068. /// Marks the played.
  1069. /// </summary>
  1070. /// <param name="user">The user.</param>
  1071. /// <param name="datePlayed">The date played.</param>
  1072. /// <param name="userManager">The user manager.</param>
  1073. /// <returns>Task.</returns>
  1074. public override async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataManager userManager)
  1075. {
  1076. // Sweep through recursively and update status
  1077. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder).Select(c => c.MarkPlayed(user, datePlayed, userManager));
  1078. await Task.WhenAll(tasks).ConfigureAwait(false);
  1079. }
  1080. /// <summary>
  1081. /// Marks the unplayed.
  1082. /// </summary>
  1083. /// <param name="user">The user.</param>
  1084. /// <param name="userManager">The user manager.</param>
  1085. /// <returns>Task.</returns>
  1086. public override async Task MarkUnplayed(User user, IUserDataManager userManager)
  1087. {
  1088. // Sweep through recursively and update status
  1089. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder).Select(c => c.MarkUnplayed(user, userManager));
  1090. await Task.WhenAll(tasks).ConfigureAwait(false);
  1091. }
  1092. /// <summary>
  1093. /// Finds an item by path, recursively
  1094. /// </summary>
  1095. /// <param name="path">The path.</param>
  1096. /// <returns>BaseItem.</returns>
  1097. /// <exception cref="System.ArgumentNullException"></exception>
  1098. public BaseItem FindByPath(string path)
  1099. {
  1100. if (string.IsNullOrEmpty(path))
  1101. {
  1102. throw new ArgumentNullException();
  1103. }
  1104. try
  1105. {
  1106. if (ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1107. {
  1108. return this;
  1109. }
  1110. }
  1111. catch (IOException ex)
  1112. {
  1113. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1114. }
  1115. //this should be functionally equivilent to what was here since it is IEnum and works on a thread-safe copy
  1116. return RecursiveChildren.FirstOrDefault(i =>
  1117. {
  1118. try
  1119. {
  1120. return i.ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase);
  1121. }
  1122. catch (IOException ex)
  1123. {
  1124. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1125. return false;
  1126. }
  1127. });
  1128. }
  1129. }
  1130. }