Folder.cs 45 KB

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