Folder.cs 36 KB

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