Folder.cs 43 KB

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