Folder.cs 43 KB

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