Folder.cs 44 KB

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