Folder.cs 44 KB

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