Folder.cs 47 KB

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