Folder.cs 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  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. AddChildInternal(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. AddChildInternal(child);
  101. }
  102. }
  103. protected void AddChildInternal(BaseItem child)
  104. {
  105. _children.Add(child);
  106. }
  107. protected void RemoveChildrenInternal(IEnumerable<BaseItem> children)
  108. {
  109. lock (ChildrenSyncLock)
  110. {
  111. _children = new ConcurrentBag<BaseItem>(_children.Except(children));
  112. }
  113. }
  114. protected void ClearChildrenInternal()
  115. {
  116. BaseItem removed;
  117. while (_children.TryTake(out removed))
  118. {
  119. }
  120. }
  121. /// <summary>
  122. /// Never want folders to be blocked by "BlockNotRated"
  123. /// </summary>
  124. [IgnoreDataMember]
  125. public override string OfficialRatingForComparison
  126. {
  127. get
  128. {
  129. if (this is Series)
  130. {
  131. return base.OfficialRatingForComparison;
  132. }
  133. return !string.IsNullOrEmpty(base.OfficialRatingForComparison) ? base.OfficialRatingForComparison : "None";
  134. }
  135. }
  136. /// <summary>
  137. /// Removes the child.
  138. /// </summary>
  139. /// <param name="item">The item.</param>
  140. /// <param name="cancellationToken">The cancellation token.</param>
  141. /// <returns>Task.</returns>
  142. /// <exception cref="System.InvalidOperationException">Unable to remove + item.Name</exception>
  143. public Task RemoveChild(BaseItem item, CancellationToken cancellationToken)
  144. {
  145. RemoveChildrenInternal(new[] { item });
  146. item.Parent = null;
  147. LibraryManager.ReportItemRemoved(item);
  148. return ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken);
  149. }
  150. #region Indexing
  151. /// <summary>
  152. /// The _index by options
  153. /// </summary>
  154. private Dictionary<string, Func<User, IEnumerable<BaseItem>>> _indexByOptions;
  155. /// <summary>
  156. /// Dictionary of index options - consists of a display value and an indexing function
  157. /// which takes User as a parameter and returns an IEnum of BaseItem
  158. /// </summary>
  159. /// <value>The index by options.</value>
  160. [IgnoreDataMember]
  161. public Dictionary<string, Func<User, IEnumerable<BaseItem>>> IndexByOptions
  162. {
  163. get { return _indexByOptions ?? (_indexByOptions = GetIndexByOptions()); }
  164. }
  165. /// <summary>
  166. /// Returns the valid set of index by options for this folder type.
  167. /// Override or extend to modify.
  168. /// </summary>
  169. /// <returns>Dictionary{System.StringFunc{UserIEnumerable{BaseItem}}}.</returns>
  170. protected virtual Dictionary<string, Func<User, IEnumerable<BaseItem>>> GetIndexByOptions()
  171. {
  172. return new Dictionary<string, Func<User, IEnumerable<BaseItem>>> {
  173. {LocalizedStrings.Instance.GetString("NoneDispPref"), null},
  174. {LocalizedStrings.Instance.GetString("PerformerDispPref"), GetIndexByPerformer},
  175. {LocalizedStrings.Instance.GetString("GenreDispPref"), GetIndexByGenre},
  176. {LocalizedStrings.Instance.GetString("DirectorDispPref"), GetIndexByDirector},
  177. {LocalizedStrings.Instance.GetString("YearDispPref"), GetIndexByYear},
  178. //{LocalizedStrings.Instance.GetString("OfficialRatingDispPref"), null},
  179. {LocalizedStrings.Instance.GetString("StudioDispPref"), GetIndexByStudio}
  180. };
  181. }
  182. /// <summary>
  183. /// Gets the index by actor.
  184. /// </summary>
  185. /// <param name="user">The user.</param>
  186. /// <returns>IEnumerable{BaseItem}.</returns>
  187. protected IEnumerable<BaseItem> GetIndexByPerformer(User user)
  188. {
  189. return GetIndexByPerson(user, new List<string> { PersonType.Actor, PersonType.GuestStar }, true, LocalizedStrings.Instance.GetString("PerformerDispPref"));
  190. }
  191. /// <summary>
  192. /// Gets the index by director.
  193. /// </summary>
  194. /// <param name="user">The user.</param>
  195. /// <returns>IEnumerable{BaseItem}.</returns>
  196. protected IEnumerable<BaseItem> GetIndexByDirector(User user)
  197. {
  198. return GetIndexByPerson(user, new List<string> { PersonType.Director }, false, LocalizedStrings.Instance.GetString("DirectorDispPref"));
  199. }
  200. /// <summary>
  201. /// Gets the index by person.
  202. /// </summary>
  203. /// <param name="user">The user.</param>
  204. /// <param name="personTypes">The person types we should match on</param>
  205. /// <param name="includeAudio">if set to <c>true</c> [include audio].</param>
  206. /// <param name="indexName">Name of the index.</param>
  207. /// <returns>IEnumerable{BaseItem}.</returns>
  208. private IEnumerable<BaseItem> GetIndexByPerson(User user, List<string> personTypes, bool includeAudio, string indexName)
  209. {
  210. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  211. // the retrieval of the individual children for each index value until they are requested.
  212. using (new Profiler(indexName + " Index Build for " + Name, Logger))
  213. {
  214. // Put this in a local variable to avoid an implicitly captured closure
  215. var currentIndexName = indexName;
  216. var us = this;
  217. var recursiveChildren = GetRecursiveChildren(user).Where(i => i.IncludeInIndex).ToList();
  218. // Get the candidates, but handle audio separately
  219. var candidates = recursiveChildren.Where(i => i.AllPeople != null && !(i is Audio.Audio)).ToList();
  220. var indexFolders = candidates.AsParallel().SelectMany(i => i.AllPeople.Where(p => personTypes.Contains(p.Type))
  221. .Select(a => a.Name))
  222. .Distinct()
  223. .Select(i =>
  224. {
  225. try
  226. {
  227. return LibraryManager.GetPerson(i);
  228. }
  229. catch (IOException ex)
  230. {
  231. Logger.ErrorException("Error getting person {0}", ex, i);
  232. return null;
  233. }
  234. catch (AggregateException ex)
  235. {
  236. Logger.ErrorException("Error getting person {0}", ex, i);
  237. return null;
  238. }
  239. })
  240. .Where(i => i != null)
  241. .Select(a => new IndexFolder(us, a,
  242. candidates.Where(i => i.AllPeople.Any(p => personTypes.Contains(p.Type) && p.Name.Equals(a.Name, StringComparison.OrdinalIgnoreCase))
  243. ), currentIndexName)).AsEnumerable();
  244. if (includeAudio)
  245. {
  246. var songs = recursiveChildren.OfType<Audio.Audio>().ToList();
  247. indexFolders = songs.SelectMany(i => i.Artists)
  248. .Distinct(StringComparer.OrdinalIgnoreCase)
  249. .Select(i =>
  250. {
  251. try
  252. {
  253. return LibraryManager.GetArtist(i);
  254. }
  255. catch (IOException ex)
  256. {
  257. Logger.ErrorException("Error getting artist {0}", ex, i);
  258. return null;
  259. }
  260. catch (AggregateException ex)
  261. {
  262. Logger.ErrorException("Error getting artist {0}", ex, i);
  263. return null;
  264. }
  265. })
  266. .Where(i => i != null)
  267. .Select(a => new IndexFolder(us, a,
  268. songs.Where(i => i.Artists.Contains(a.Name, StringComparer.OrdinalIgnoreCase)
  269. ), currentIndexName)).Concat(indexFolders);
  270. }
  271. return indexFolders;
  272. }
  273. }
  274. /// <summary>
  275. /// Gets the index by studio.
  276. /// </summary>
  277. /// <param name="user">The user.</param>
  278. /// <returns>IEnumerable{BaseItem}.</returns>
  279. protected IEnumerable<BaseItem> GetIndexByStudio(User user)
  280. {
  281. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  282. // the retrieval of the individual children for each index value until they are requested.
  283. using (new Profiler("Studio Index Build for " + Name, Logger))
  284. {
  285. var indexName = LocalizedStrings.Instance.GetString("StudioDispPref");
  286. var candidates = GetRecursiveChildren(user).Where(i => i.IncludeInIndex).ToList();
  287. return candidates.AsParallel().SelectMany(i => i.AllStudios)
  288. .Distinct()
  289. .Select(i =>
  290. {
  291. try
  292. {
  293. return LibraryManager.GetStudio(i);
  294. }
  295. catch (IOException ex)
  296. {
  297. Logger.ErrorException("Error getting studio {0}", ex, i);
  298. return null;
  299. }
  300. catch (AggregateException ex)
  301. {
  302. Logger.ErrorException("Error getting studio {0}", ex, i);
  303. return null;
  304. }
  305. })
  306. .Where(i => i != null)
  307. .Select(ndx => new IndexFolder(this, ndx, candidates.Where(i => i.AllStudios.Any(s => s.Equals(ndx.Name, StringComparison.OrdinalIgnoreCase))), indexName));
  308. }
  309. }
  310. /// <summary>
  311. /// Gets the index by genre.
  312. /// </summary>
  313. /// <param name="user">The user.</param>
  314. /// <returns>IEnumerable{BaseItem}.</returns>
  315. protected IEnumerable<BaseItem> GetIndexByGenre(User user)
  316. {
  317. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  318. // the retrieval of the individual children for each index value until they are requested.
  319. using (new Profiler("Genre Index Build for " + Name, Logger))
  320. {
  321. var indexName = LocalizedStrings.Instance.GetString("GenreDispPref");
  322. //we need a copy of this so we don't double-recurse
  323. var candidates = GetRecursiveChildren(user).Where(i => i.IncludeInIndex).ToList();
  324. return candidates.AsParallel().SelectMany(i => i.AllGenres)
  325. .Distinct(StringComparer.OrdinalIgnoreCase)
  326. .Select(i =>
  327. {
  328. try
  329. {
  330. return LibraryManager.GetGenre(i);
  331. }
  332. catch (Exception 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);
  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 = null;
  389. var cacheKey = user.Name + indexBy;
  390. if (IndexCache != null)
  391. {
  392. IndexCache.TryGetValue(cacheKey, out result);
  393. }
  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;
  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. if (IndexCache == null)
  426. {
  427. IndexCache = new ConcurrentDictionary<string, List<BaseItem>>();
  428. }
  429. return indexFunction != null
  430. ? IndexCache[user.Name + indexKey] = indexFunction(user).ToList()
  431. : null;
  432. }
  433. #endregion
  434. /// <summary>
  435. /// The children
  436. /// </summary>
  437. private ConcurrentBag<BaseItem> _children;
  438. /// <summary>
  439. /// The _children initialized
  440. /// </summary>
  441. private bool _childrenInitialized;
  442. /// <summary>
  443. /// The _children sync lock
  444. /// </summary>
  445. protected object ChildrenSyncLock = new object();
  446. /// <summary>
  447. /// Gets or sets the actual children.
  448. /// </summary>
  449. /// <value>The actual children.</value>
  450. protected virtual IEnumerable<BaseItem> ActualChildren
  451. {
  452. get
  453. {
  454. LazyInitializer.EnsureInitialized(ref _children, ref _childrenInitialized, ref ChildrenSyncLock, LoadChildrenInternal);
  455. return _children;
  456. }
  457. }
  458. /// <summary>
  459. /// thread-safe access to the actual children of this folder - without regard to user
  460. /// </summary>
  461. /// <value>The children.</value>
  462. [IgnoreDataMember]
  463. public IEnumerable<BaseItem> Children
  464. {
  465. get { return ActualChildren; }
  466. }
  467. /// <summary>
  468. /// thread-safe access to all recursive children of this folder - without regard to user
  469. /// </summary>
  470. /// <value>The recursive children.</value>
  471. [IgnoreDataMember]
  472. public IEnumerable<BaseItem> RecursiveChildren
  473. {
  474. get
  475. {
  476. foreach (var item in Children)
  477. {
  478. yield return item;
  479. if (item.IsFolder)
  480. {
  481. var subFolder = (Folder)item;
  482. foreach (var subitem in subFolder.RecursiveChildren)
  483. {
  484. yield return subitem;
  485. }
  486. }
  487. }
  488. }
  489. }
  490. private ConcurrentBag<BaseItem> LoadChildrenInternal()
  491. {
  492. return new ConcurrentBag<BaseItem>(LoadChildren());
  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 IEnumerable<BaseItem> LoadChildren()
  500. {
  501. //just load our children from the repo - the library will be validated and maintained in other processes
  502. return GetCachedChildren();
  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.ToDictionary(i => i.Id);
  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, false);
  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. var actualRemovals = new List<BaseItem>();
  625. foreach (var item in itemsRemoved)
  626. {
  627. if (IsRootPathAvailable(item.Path))
  628. {
  629. item.IsOffline = false;
  630. actualRemovals.Add(item);
  631. }
  632. else
  633. {
  634. item.IsOffline = true;
  635. validChildren.Add(new Tuple<BaseItem, bool>(item, false));
  636. }
  637. }
  638. if (actualRemovals.Count > 0)
  639. {
  640. RemoveChildrenInternal(actualRemovals);
  641. }
  642. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  643. foreach (var item in newItems)
  644. {
  645. _children.Add(item);
  646. Logger.Debug("** " + item.Name + " Added to library.");
  647. }
  648. await ItemRepository.SaveChildren(Id, _children.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  649. //force the indexes to rebuild next time
  650. if (IndexCache != null)
  651. {
  652. IndexCache.Clear();
  653. }
  654. }
  655. progress.Report(10);
  656. cancellationToken.ThrowIfCancellationRequested();
  657. await RefreshChildren(validChildren, progress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  658. progress.Report(100);
  659. }
  660. /// <summary>
  661. /// Refreshes the children.
  662. /// </summary>
  663. /// <param name="children">The children.</param>
  664. /// <param name="progress">The progress.</param>
  665. /// <param name="cancellationToken">The cancellation token.</param>
  666. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  667. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  668. /// <returns>Task.</returns>
  669. private async Task RefreshChildren(IEnumerable<Tuple<BaseItem, bool>> children, IProgress<double> progress, CancellationToken cancellationToken, bool? recursive, bool forceRefreshMetadata = false)
  670. {
  671. var list = children.ToList();
  672. var percentages = new Dictionary<Guid, double>(list.Count);
  673. var tasks = new List<Task>();
  674. foreach (var tuple in list)
  675. {
  676. if (tasks.Count > 8)
  677. {
  678. await Task.WhenAll(tasks).ConfigureAwait(false);
  679. }
  680. Tuple<BaseItem, bool> currentTuple = tuple;
  681. tasks.Add(Task.Run(async () =>
  682. {
  683. cancellationToken.ThrowIfCancellationRequested();
  684. var child = currentTuple.Item1;
  685. //refresh it
  686. await child.RefreshMetadata(cancellationToken, forceSave: currentTuple.Item2, forceRefresh: forceRefreshMetadata, resetResolveArgs: false).ConfigureAwait(false);
  687. // Refresh children if a folder and the item changed or recursive is set to true
  688. var refreshChildren = child.IsFolder && (currentTuple.Item2 || (recursive.HasValue && recursive.Value));
  689. if (refreshChildren)
  690. {
  691. // Don't refresh children if explicitly set to false
  692. if (recursive.HasValue && recursive.Value == false)
  693. {
  694. refreshChildren = false;
  695. }
  696. }
  697. if (refreshChildren)
  698. {
  699. cancellationToken.ThrowIfCancellationRequested();
  700. var innerProgress = new ActionableProgress<double>();
  701. innerProgress.RegisterAction(p =>
  702. {
  703. lock (percentages)
  704. {
  705. percentages[child.Id] = p / 100;
  706. var percent = percentages.Values.Sum();
  707. percent /= list.Count;
  708. progress.Report((90 * percent) + 10);
  709. }
  710. });
  711. await ((Folder)child).ValidateChildren(innerProgress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  712. // Some folder providers are unable to refresh until children have been refreshed.
  713. await child.RefreshMetadata(cancellationToken, resetResolveArgs: false).ConfigureAwait(false);
  714. }
  715. else
  716. {
  717. lock (percentages)
  718. {
  719. percentages[child.Id] = 1;
  720. var percent = percentages.Values.Sum();
  721. percent /= list.Count;
  722. progress.Report((90 * percent) + 10);
  723. }
  724. }
  725. }));
  726. }
  727. cancellationToken.ThrowIfCancellationRequested();
  728. await Task.WhenAll(tasks).ConfigureAwait(false);
  729. }
  730. /// <summary>
  731. /// Determines if a path's root is available or not
  732. /// </summary>
  733. /// <param name="path"></param>
  734. /// <returns></returns>
  735. private bool IsRootPathAvailable(string path)
  736. {
  737. if (File.Exists(path))
  738. {
  739. return true;
  740. }
  741. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  742. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  743. {
  744. if (Directory.Exists(path))
  745. {
  746. return true;
  747. }
  748. path = System.IO.Path.GetDirectoryName(path);
  749. }
  750. return false;
  751. }
  752. /// <summary>
  753. /// Get the children of this folder from the actual file system
  754. /// </summary>
  755. /// <returns>IEnumerable{BaseItem}.</returns>
  756. protected virtual IEnumerable<BaseItem> GetNonCachedChildren()
  757. {
  758. if (ResolveArgs == null || ResolveArgs.FileSystemDictionary == null)
  759. {
  760. Logger.Error("Null for {0}", Path);
  761. }
  762. return LibraryManager.ResolvePaths<BaseItem>(ResolveArgs.FileSystemChildren, this);
  763. }
  764. /// <summary>
  765. /// Get our children from the repo - stubbed for now
  766. /// </summary>
  767. /// <returns>IEnumerable{BaseItem}.</returns>
  768. protected IEnumerable<BaseItem> GetCachedChildren()
  769. {
  770. return ItemRepository.GetChildren(Id).Select(RetrieveChild).Where(i => i != null);
  771. }
  772. /// <summary>
  773. /// Retrieves the child.
  774. /// </summary>
  775. /// <param name="child">The child.</param>
  776. /// <returns>BaseItem.</returns>
  777. private BaseItem RetrieveChild(Guid child)
  778. {
  779. var item = LibraryManager.RetrieveItem(child);
  780. if (item != null)
  781. {
  782. if (item is IByReferenceItem)
  783. {
  784. return LibraryManager.GetOrAddByReferenceItem(item);
  785. }
  786. item.Parent = this;
  787. }
  788. return item;
  789. }
  790. /// <summary>
  791. /// Gets allowed children of an item
  792. /// </summary>
  793. /// <param name="user">The user.</param>
  794. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  795. /// <param name="indexBy">The index by.</param>
  796. /// <returns>IEnumerable{BaseItem}.</returns>
  797. /// <exception cref="System.ArgumentNullException"></exception>
  798. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren, string indexBy = null)
  799. {
  800. if (user == null)
  801. {
  802. throw new ArgumentNullException();
  803. }
  804. //the true root should return our users root folder children
  805. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren, indexBy);
  806. IEnumerable<BaseItem> result = null;
  807. if (!string.IsNullOrEmpty(indexBy))
  808. {
  809. result = GetIndexedChildren(user, indexBy);
  810. }
  811. if (result != null)
  812. {
  813. return result;
  814. }
  815. return GetChildrenList(user, includeLinkedChildren);
  816. }
  817. /// <summary>
  818. /// Gets the children list.
  819. /// </summary>
  820. /// <param name="user">The user.</param>
  821. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  822. /// <returns>List{BaseItem}.</returns>
  823. private List<BaseItem> GetChildrenList(User user, bool includeLinkedChildren)
  824. {
  825. var list = new List<BaseItem>();
  826. foreach (var child in Children)
  827. {
  828. if (child.IsVisible(user))
  829. {
  830. list.Add(child);
  831. }
  832. }
  833. if (includeLinkedChildren)
  834. {
  835. foreach (var child in GetLinkedChildren())
  836. {
  837. if (child.IsVisible(user))
  838. {
  839. list.Add(child);
  840. }
  841. }
  842. }
  843. return list;
  844. }
  845. /// <summary>
  846. /// Gets allowed recursive children of an item
  847. /// </summary>
  848. /// <param name="user">The user.</param>
  849. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  850. /// <returns>IEnumerable{BaseItem}.</returns>
  851. /// <exception cref="System.ArgumentNullException"></exception>
  852. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  853. {
  854. if (user == null)
  855. {
  856. throw new ArgumentNullException();
  857. }
  858. var list = new List<BaseItem>(10000);
  859. AddRecursiveChildrenInternal(user, includeLinkedChildren, list);
  860. if (includeLinkedChildren)
  861. {
  862. list = list.Distinct().ToList();
  863. }
  864. return list;
  865. }
  866. /// <summary>
  867. /// Adds the recursive children internal.
  868. /// </summary>
  869. /// <param name="user">The user.</param>
  870. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  871. /// <param name="list">The list.</param>
  872. private void AddRecursiveChildrenInternal(User user, bool includeLinkedChildren, List<BaseItem> list)
  873. {
  874. foreach (var item in GetChildrenList(user, includeLinkedChildren))
  875. {
  876. list.Add(item);
  877. var subFolder = item as Folder;
  878. if (subFolder != null)
  879. {
  880. subFolder.AddRecursiveChildrenInternal(user, includeLinkedChildren, list);
  881. }
  882. }
  883. }
  884. /// <summary>
  885. /// Gets the linked children.
  886. /// </summary>
  887. /// <returns>IEnumerable{BaseItem}.</returns>
  888. public IEnumerable<BaseItem> GetLinkedChildren()
  889. {
  890. return LinkedChildren
  891. .Select(GetLinkedChild)
  892. .Where(i => i != null);
  893. }
  894. /// <summary>
  895. /// Gets the linked child.
  896. /// </summary>
  897. /// <param name="info">The info.</param>
  898. /// <returns>BaseItem.</returns>
  899. private BaseItem GetLinkedChild(LinkedChild info)
  900. {
  901. if (string.IsNullOrEmpty(info.Path))
  902. {
  903. throw new ArgumentException("Encountered linked child with empty path.");
  904. }
  905. var item = LibraryManager.RootFolder.FindByPath(info.Path);
  906. if (item == null)
  907. {
  908. Logger.Warn("Unable to find linked item at {0}", info.Path);
  909. }
  910. return item;
  911. }
  912. public override async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  913. {
  914. var changed = await base.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs).ConfigureAwait(false);
  915. return changed || (SupportsShortcutChildren && LocationType == LocationType.FileSystem && RefreshLinkedChildren());
  916. }
  917. /// <summary>
  918. /// Refreshes the linked children.
  919. /// </summary>
  920. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  921. private bool RefreshLinkedChildren()
  922. {
  923. ItemResolveArgs resolveArgs;
  924. try
  925. {
  926. resolveArgs = ResolveArgs;
  927. if (!resolveArgs.IsDirectory)
  928. {
  929. return false;
  930. }
  931. }
  932. catch (IOException ex)
  933. {
  934. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  935. return false;
  936. }
  937. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  938. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  939. var newShortcutLinks = resolveArgs.FileSystemChildren
  940. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  941. .Select(i =>
  942. {
  943. try
  944. {
  945. Logger.Debug("Found shortcut at {0}", i.FullName);
  946. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  947. if (!string.IsNullOrEmpty(resolvedPath))
  948. {
  949. return new LinkedChild
  950. {
  951. Path = resolvedPath,
  952. Type = LinkedChildType.Shortcut
  953. };
  954. }
  955. Logger.Error("Error resolving shortcut {0}", i.FullName);
  956. return null;
  957. }
  958. catch (IOException ex)
  959. {
  960. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  961. return null;
  962. }
  963. })
  964. .Where(i => i != null)
  965. .ToList();
  966. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks))
  967. {
  968. Logger.Info("Shortcut links have changed for {0}", Path);
  969. newShortcutLinks.AddRange(currentManualLinks);
  970. LinkedChildren = newShortcutLinks;
  971. return true;
  972. }
  973. return false;
  974. }
  975. /// <summary>
  976. /// Folders need to validate and refresh
  977. /// </summary>
  978. /// <returns>Task.</returns>
  979. public override async Task ChangedExternally()
  980. {
  981. await base.ChangedExternally().ConfigureAwait(false);
  982. var progress = new Progress<double>();
  983. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  984. }
  985. /// <summary>
  986. /// Marks the played.
  987. /// </summary>
  988. /// <param name="user">The user.</param>
  989. /// <param name="datePlayed">The date played.</param>
  990. /// <param name="userManager">The user manager.</param>
  991. /// <returns>Task.</returns>
  992. public override async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataRepository userManager)
  993. {
  994. // Sweep through recursively and update status
  995. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder).Select(c => c.MarkPlayed(user, datePlayed, userManager));
  996. await Task.WhenAll(tasks).ConfigureAwait(false);
  997. }
  998. /// <summary>
  999. /// Marks the unplayed.
  1000. /// </summary>
  1001. /// <param name="user">The user.</param>
  1002. /// <param name="userManager">The user manager.</param>
  1003. /// <returns>Task.</returns>
  1004. public override async Task MarkUnplayed(User user, IUserDataRepository userManager)
  1005. {
  1006. // Sweep through recursively and update status
  1007. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder).Select(c => c.MarkUnplayed(user, userManager));
  1008. await Task.WhenAll(tasks).ConfigureAwait(false);
  1009. }
  1010. /// <summary>
  1011. /// Finds an item by path, recursively
  1012. /// </summary>
  1013. /// <param name="path">The path.</param>
  1014. /// <returns>BaseItem.</returns>
  1015. /// <exception cref="System.ArgumentNullException"></exception>
  1016. public BaseItem FindByPath(string path)
  1017. {
  1018. if (string.IsNullOrEmpty(path))
  1019. {
  1020. throw new ArgumentNullException();
  1021. }
  1022. try
  1023. {
  1024. if (ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1025. {
  1026. return this;
  1027. }
  1028. }
  1029. catch (IOException ex)
  1030. {
  1031. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1032. }
  1033. //this should be functionally equivilent to what was here since it is IEnum and works on a thread-safe copy
  1034. return RecursiveChildren.FirstOrDefault(i =>
  1035. {
  1036. try
  1037. {
  1038. return i.ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase);
  1039. }
  1040. catch (IOException ex)
  1041. {
  1042. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1043. return false;
  1044. }
  1045. });
  1046. }
  1047. }
  1048. }