Folder.cs 39 KB

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