Folder.cs 39 KB

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