Folder.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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 SupportsShortcutChildren
  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. var locationType = LocationType;
  571. // Nothing to do here
  572. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  573. {
  574. return;
  575. }
  576. cancellationToken.ThrowIfCancellationRequested();
  577. //get the current valid children from filesystem (or wherever)
  578. var nonCachedChildren = IsOffline ? new BaseItem[] { } : GetNonCachedChildren();
  579. if (nonCachedChildren == null) return; //nothing to validate
  580. progress.Report(5);
  581. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  582. var currentChildren = ActualChildren;
  583. //create a list for our validated children
  584. var validChildren = new ConcurrentBag<Tuple<BaseItem, bool>>();
  585. var newItems = new ConcurrentBag<BaseItem>();
  586. cancellationToken.ThrowIfCancellationRequested();
  587. var options = new ParallelOptions
  588. {
  589. MaxDegreeOfParallelism = 20
  590. };
  591. Parallel.ForEach(nonCachedChildren, options, child =>
  592. {
  593. BaseItem currentChild;
  594. if (currentChildren.TryGetValue(child.Id, out currentChild))
  595. {
  596. currentChild.ResolveArgs = child.ResolveArgs;
  597. //existing item - check if it has changed
  598. if (currentChild.HasChanged(child))
  599. {
  600. EntityResolutionHelper.EnsureDates(currentChild, child.ResolveArgs);
  601. validChildren.Add(new Tuple<BaseItem, bool>(currentChild, true));
  602. }
  603. else
  604. {
  605. validChildren.Add(new Tuple<BaseItem, bool>(currentChild, false));
  606. }
  607. }
  608. else
  609. {
  610. //brand new item - needs to be added
  611. newItems.Add(child);
  612. validChildren.Add(new Tuple<BaseItem, bool>(child, true));
  613. }
  614. });
  615. // If any items were added or removed....
  616. if (!newItems.IsEmpty || currentChildren.Count != validChildren.Count)
  617. {
  618. var newChildren = validChildren.Select(c => c.Item1).ToList();
  619. //that's all the new and changed ones - now see if there are any that are missing
  620. var itemsRemoved = currentChildren.Values.Except(newChildren).ToList();
  621. foreach (var item in itemsRemoved)
  622. {
  623. if (IsRootPathAvailable(item.Path))
  624. {
  625. BaseItem removed;
  626. if (!_children.TryRemove(item.Id, out removed))
  627. {
  628. Logger.Error("Failed to remove {0}", item.Name);
  629. }
  630. else
  631. {
  632. LibraryManager.ReportItemRemoved(item);
  633. }
  634. item.IsOffline = false;
  635. }
  636. else
  637. {
  638. item.IsOffline = true;
  639. validChildren.Add(new Tuple<BaseItem, bool>(item, false));
  640. }
  641. }
  642. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  643. foreach (var item in newItems)
  644. {
  645. if (!_children.TryAdd(item.Id, item))
  646. {
  647. Logger.Error("Failed to add {0}", item.Name);
  648. }
  649. else
  650. {
  651. Logger.Debug("** " + item.Name + " Added to library.");
  652. }
  653. }
  654. await ItemRepository.SaveChildren(Id, _children.Values.ToList().Select(i => i.Id), cancellationToken).ConfigureAwait(false);
  655. //force the indexes to rebuild next time
  656. IndexCache.Clear();
  657. }
  658. progress.Report(10);
  659. cancellationToken.ThrowIfCancellationRequested();
  660. await RefreshChildren(validChildren, progress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  661. progress.Report(100);
  662. }
  663. /// <summary>
  664. /// Refreshes the children.
  665. /// </summary>
  666. /// <param name="children">The children.</param>
  667. /// <param name="progress">The progress.</param>
  668. /// <param name="cancellationToken">The cancellation token.</param>
  669. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  670. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  671. /// <returns>Task.</returns>
  672. private async Task RefreshChildren(IEnumerable<Tuple<BaseItem, bool>> children, IProgress<double> progress, CancellationToken cancellationToken, bool? recursive, bool forceRefreshMetadata = false)
  673. {
  674. var list = children.ToList();
  675. var percentages = new Dictionary<Guid, double>();
  676. var tasks = new List<Task>();
  677. foreach (var tuple in list)
  678. {
  679. if (tasks.Count > 8)
  680. {
  681. await Task.WhenAll(tasks).ConfigureAwait(false);
  682. }
  683. Tuple<BaseItem, bool> currentTuple = tuple;
  684. tasks.Add(Task.Run(async () =>
  685. {
  686. cancellationToken.ThrowIfCancellationRequested();
  687. var child = currentTuple.Item1;
  688. //refresh it
  689. await child.RefreshMetadata(cancellationToken, forceSave: currentTuple.Item2, forceRefresh: forceRefreshMetadata, resetResolveArgs: false).ConfigureAwait(false);
  690. // Refresh children if a folder and the item changed or recursive is set to true
  691. var refreshChildren = child.IsFolder && (currentTuple.Item2 || (recursive.HasValue && recursive.Value));
  692. if (refreshChildren)
  693. {
  694. // Don't refresh children if explicitly set to false
  695. if (recursive.HasValue && recursive.Value == false)
  696. {
  697. refreshChildren = false;
  698. }
  699. }
  700. if (refreshChildren)
  701. {
  702. cancellationToken.ThrowIfCancellationRequested();
  703. var innerProgress = new ActionableProgress<double>();
  704. innerProgress.RegisterAction(p =>
  705. {
  706. lock (percentages)
  707. {
  708. percentages[child.Id] = p / 100;
  709. var percent = percentages.Values.Sum();
  710. percent /= list.Count;
  711. progress.Report((90 * percent) + 10);
  712. }
  713. });
  714. await ((Folder)child).ValidateChildren(innerProgress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  715. // Some folder providers are unable to refresh until children have been refreshed.
  716. await child.RefreshMetadata(cancellationToken, resetResolveArgs: false).ConfigureAwait(false);
  717. }
  718. else
  719. {
  720. lock (percentages)
  721. {
  722. percentages[child.Id] = 1;
  723. var percent = percentages.Values.Sum();
  724. percent /= list.Count;
  725. progress.Report((90 * percent) + 10);
  726. }
  727. }
  728. }));
  729. }
  730. cancellationToken.ThrowIfCancellationRequested();
  731. await Task.WhenAll(tasks).ConfigureAwait(false);
  732. }
  733. /// <summary>
  734. /// Determines if a path's root is available or not
  735. /// </summary>
  736. /// <param name="path"></param>
  737. /// <returns></returns>
  738. private bool IsRootPathAvailable(string path)
  739. {
  740. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  741. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  742. {
  743. if (Directory.Exists(path))
  744. {
  745. return true;
  746. }
  747. path = System.IO.Path.GetDirectoryName(path);
  748. }
  749. return false;
  750. }
  751. /// <summary>
  752. /// Get the children of this folder from the actual file system
  753. /// </summary>
  754. /// <returns>IEnumerable{BaseItem}.</returns>
  755. protected virtual IEnumerable<BaseItem> GetNonCachedChildren()
  756. {
  757. IEnumerable<FileSystemInfo> fileSystemChildren;
  758. try
  759. {
  760. fileSystemChildren = ResolveArgs.FileSystemChildren;
  761. }
  762. catch (IOException ex)
  763. {
  764. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  765. return new List<BaseItem>();
  766. }
  767. return LibraryManager.ResolvePaths<BaseItem>(fileSystemChildren, this);
  768. }
  769. /// <summary>
  770. /// Get our children from the repo - stubbed for now
  771. /// </summary>
  772. /// <returns>IEnumerable{BaseItem}.</returns>
  773. protected IEnumerable<BaseItem> GetCachedChildren()
  774. {
  775. return ItemRepository.GetChildren(Id).Select(RetrieveChild).Where(i => i != null);
  776. }
  777. /// <summary>
  778. /// Retrieves the child.
  779. /// </summary>
  780. /// <param name="child">The child.</param>
  781. /// <returns>BaseItem.</returns>
  782. private BaseItem RetrieveChild(Guid child)
  783. {
  784. var item = LibraryManager.RetrieveItem(child);
  785. if (item != null)
  786. {
  787. if (item is IByReferenceItem)
  788. {
  789. return LibraryManager.GetOrAddByReferenceItem(item);
  790. }
  791. item.Parent = this;
  792. }
  793. return item;
  794. }
  795. /// <summary>
  796. /// Gets allowed children of an item
  797. /// </summary>
  798. /// <param name="user">The user.</param>
  799. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  800. /// <param name="indexBy">The index by.</param>
  801. /// <returns>IEnumerable{BaseItem}.</returns>
  802. /// <exception cref="System.ArgumentNullException"></exception>
  803. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren, string indexBy = null)
  804. {
  805. if (user == null)
  806. {
  807. throw new ArgumentNullException();
  808. }
  809. //the true root should return our users root folder children
  810. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren, indexBy);
  811. IEnumerable<BaseItem> result = null;
  812. if (!string.IsNullOrEmpty(indexBy))
  813. {
  814. result = GetIndexedChildren(user, indexBy);
  815. }
  816. if (result != null)
  817. {
  818. return result;
  819. }
  820. var children = Children;
  821. if (includeLinkedChildren)
  822. {
  823. children = children.Concat(GetLinkedChildren());
  824. }
  825. // If indexed is false or the indexing function is null
  826. return children.Where(c => c.IsVisible(user));
  827. }
  828. /// <summary>
  829. /// Gets allowed recursive children of an item
  830. /// </summary>
  831. /// <param name="user">The user.</param>
  832. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  833. /// <returns>IEnumerable{BaseItem}.</returns>
  834. /// <exception cref="System.ArgumentNullException"></exception>
  835. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = false)
  836. {
  837. if (user == null)
  838. {
  839. throw new ArgumentNullException();
  840. }
  841. foreach (var item in GetChildren(user, includeLinkedChildren))
  842. {
  843. yield return item;
  844. var subFolder = item as Folder;
  845. if (subFolder != null)
  846. {
  847. foreach (var subitem in subFolder.GetRecursiveChildren(user, includeLinkedChildren))
  848. {
  849. yield return subitem;
  850. }
  851. }
  852. }
  853. }
  854. /// <summary>
  855. /// Gets the linked children.
  856. /// </summary>
  857. /// <returns>IEnumerable{BaseItem}.</returns>
  858. public IEnumerable<BaseItem> GetLinkedChildren()
  859. {
  860. return LinkedChildren
  861. .Select(GetLinkedChild)
  862. .Where(i => i != null);
  863. }
  864. /// <summary>
  865. /// Gets the linked child.
  866. /// </summary>
  867. /// <param name="info">The info.</param>
  868. /// <returns>BaseItem.</returns>
  869. private BaseItem GetLinkedChild(LinkedChild info)
  870. {
  871. var item = LibraryManager.RootFolder.FindByPath(info.Path);
  872. if (item == null)
  873. {
  874. Logger.Warn("Unable to find linked item at {0}", info.Path);
  875. }
  876. return item;
  877. }
  878. public override async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  879. {
  880. var changed = await base.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs).ConfigureAwait(false);
  881. return changed || (SupportsShortcutChildren && LocationType == LocationType.FileSystem && RefreshLinkedChildren());
  882. }
  883. /// <summary>
  884. /// Refreshes the linked children.
  885. /// </summary>
  886. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  887. private bool RefreshLinkedChildren()
  888. {
  889. ItemResolveArgs resolveArgs;
  890. try
  891. {
  892. resolveArgs = ResolveArgs;
  893. if (!resolveArgs.IsDirectory)
  894. {
  895. return false;
  896. }
  897. }
  898. catch (IOException ex)
  899. {
  900. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  901. return false;
  902. }
  903. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  904. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  905. var newShortcutLinks = resolveArgs.FileSystemChildren
  906. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  907. .Select(i =>
  908. {
  909. try
  910. {
  911. return new LinkedChild
  912. {
  913. Path = FileSystem.ResolveShortcut(i.FullName),
  914. Type = LinkedChildType.Shortcut
  915. };
  916. }
  917. catch (IOException ex)
  918. {
  919. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  920. return null;
  921. }
  922. })
  923. .Where(i => i != null)
  924. .ToList();
  925. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks))
  926. {
  927. Logger.Info("Shortcut links have changed for {0}", Path);
  928. newShortcutLinks.AddRange(currentManualLinks);
  929. LinkedChildren = newShortcutLinks;
  930. return true;
  931. }
  932. return false;
  933. }
  934. /// <summary>
  935. /// Folders need to validate and refresh
  936. /// </summary>
  937. /// <returns>Task.</returns>
  938. public override async Task ChangedExternally()
  939. {
  940. await base.ChangedExternally().ConfigureAwait(false);
  941. var progress = new Progress<double>();
  942. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  943. }
  944. /// <summary>
  945. /// Marks the item as either played or unplayed
  946. /// </summary>
  947. /// <param name="user">The user.</param>
  948. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  949. /// <param name="userManager">The user manager.</param>
  950. /// <returns>Task.</returns>
  951. public override async Task SetPlayedStatus(User user, bool wasPlayed, IUserDataRepository userManager)
  952. {
  953. // Sweep through recursively and update status
  954. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder).Select(c => c.SetPlayedStatus(user, wasPlayed, userManager));
  955. await Task.WhenAll(tasks).ConfigureAwait(false);
  956. }
  957. /// <summary>
  958. /// Finds an item by path, recursively
  959. /// </summary>
  960. /// <param name="path">The path.</param>
  961. /// <returns>BaseItem.</returns>
  962. /// <exception cref="System.ArgumentNullException"></exception>
  963. public BaseItem FindByPath(string path)
  964. {
  965. if (string.IsNullOrEmpty(path))
  966. {
  967. throw new ArgumentNullException();
  968. }
  969. try
  970. {
  971. if (ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  972. {
  973. return this;
  974. }
  975. }
  976. catch (IOException ex)
  977. {
  978. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  979. }
  980. //this should be functionally equivilent to what was here since it is IEnum and works on a thread-safe copy
  981. return RecursiveChildren.FirstOrDefault(i =>
  982. {
  983. try
  984. {
  985. return i.ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase);
  986. }
  987. catch (IOException ex)
  988. {
  989. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  990. return false;
  991. }
  992. });
  993. }
  994. }
  995. }