Folder.cs 37 KB

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