Folder.cs 39 KB

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