Folder.cs 45 KB

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