Folder.cs 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  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 SupportsShortcutChildren
  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 = IsOffline ? new BaseItem[] { } : 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. validChildren.Add(new Tuple<BaseItem, bool>(item, false));
  640. }
  641. }
  642. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  643. foreach (var item in newItems)
  644. {
  645. if (!_children.TryAdd(item.Id, item))
  646. {
  647. Logger.Error("Failed to add {0}", item.Name);
  648. }
  649. else
  650. {
  651. Logger.Debug("** " + item.Name + " Added to library.");
  652. }
  653. }
  654. await ItemRepository.SaveChildren(Id, _children.Values.ToList().Select(i => i.Id), cancellationToken).ConfigureAwait(false);
  655. //force the indexes to rebuild next time
  656. IndexCache.Clear();
  657. }
  658. progress.Report(10);
  659. cancellationToken.ThrowIfCancellationRequested();
  660. await RefreshChildren(validChildren, progress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  661. progress.Report(100);
  662. }
  663. /// <summary>
  664. /// Refreshes the children.
  665. /// </summary>
  666. /// <param name="children">The children.</param>
  667. /// <param name="progress">The progress.</param>
  668. /// <param name="cancellationToken">The cancellation token.</param>
  669. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  670. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  671. /// <returns>Task.</returns>
  672. private async Task RefreshChildren(IEnumerable<Tuple<BaseItem, bool>> children, IProgress<double> progress, CancellationToken cancellationToken, bool? recursive, bool forceRefreshMetadata = false)
  673. {
  674. var list = children.ToList();
  675. var percentages = new Dictionary<Guid, double>();
  676. var tasks = new List<Task>();
  677. foreach (var tuple in list)
  678. {
  679. if (tasks.Count > 8)
  680. {
  681. await Task.WhenAll(tasks).ConfigureAwait(false);
  682. }
  683. Tuple<BaseItem, bool> currentTuple = tuple;
  684. tasks.Add(Task.Run(async () =>
  685. {
  686. cancellationToken.ThrowIfCancellationRequested();
  687. var child = currentTuple.Item1;
  688. //refresh it
  689. await child.RefreshMetadata(cancellationToken, forceSave: currentTuple.Item2, forceRefresh: forceRefreshMetadata, resetResolveArgs: false).ConfigureAwait(false);
  690. // Refresh children if a folder and the item changed or recursive is set to true
  691. var refreshChildren = child.IsFolder && (currentTuple.Item2 || (recursive.HasValue && recursive.Value));
  692. if (refreshChildren)
  693. {
  694. // Don't refresh children if explicitly set to false
  695. if (recursive.HasValue && recursive.Value == false)
  696. {
  697. refreshChildren = false;
  698. }
  699. }
  700. if (refreshChildren)
  701. {
  702. cancellationToken.ThrowIfCancellationRequested();
  703. var innerProgress = new ActionableProgress<double>();
  704. innerProgress.RegisterAction(p =>
  705. {
  706. lock (percentages)
  707. {
  708. percentages[child.Id] = p / 100;
  709. var percent = percentages.Values.Sum();
  710. percent /= list.Count;
  711. progress.Report((90 * percent) + 10);
  712. }
  713. });
  714. await ((Folder)child).ValidateChildren(innerProgress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  715. // Some folder providers are unable to refresh until children have been refreshed.
  716. await child.RefreshMetadata(cancellationToken, resetResolveArgs: false).ConfigureAwait(false);
  717. }
  718. else
  719. {
  720. lock (percentages)
  721. {
  722. percentages[child.Id] = 1;
  723. var percent = percentages.Values.Sum();
  724. percent /= list.Count;
  725. progress.Report((90 * percent) + 10);
  726. }
  727. }
  728. }));
  729. }
  730. cancellationToken.ThrowIfCancellationRequested();
  731. await Task.WhenAll(tasks).ConfigureAwait(false);
  732. }
  733. /// <summary>
  734. /// Determines if a path's root is available or not
  735. /// </summary>
  736. /// <param name="path"></param>
  737. /// <returns></returns>
  738. private bool IsRootPathAvailable(string path)
  739. {
  740. var parent = System.IO.Path.GetDirectoryName(path);
  741. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  742. while (!string.IsNullOrEmpty(parent) && !parent.ToCharArray()[0].Equals(System.IO.Path.DirectorySeparatorChar))
  743. {
  744. if (Directory.Exists(parent))
  745. {
  746. return true;
  747. }
  748. parent = System.IO.Path.GetDirectoryName(path);
  749. }
  750. return false;
  751. }
  752. /// <summary>
  753. /// Get the children of this folder from the actual file system
  754. /// </summary>
  755. /// <returns>IEnumerable{BaseItem}.</returns>
  756. protected virtual IEnumerable<BaseItem> GetNonCachedChildren()
  757. {
  758. IEnumerable<FileSystemInfo> fileSystemChildren;
  759. try
  760. {
  761. fileSystemChildren = ResolveArgs.FileSystemChildren;
  762. }
  763. catch (IOException ex)
  764. {
  765. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  766. return new List<BaseItem>();
  767. }
  768. return LibraryManager.ResolvePaths<BaseItem>(fileSystemChildren, this);
  769. }
  770. /// <summary>
  771. /// Get our children from the repo - stubbed for now
  772. /// </summary>
  773. /// <returns>IEnumerable{BaseItem}.</returns>
  774. protected IEnumerable<BaseItem> GetCachedChildren()
  775. {
  776. return ItemRepository.GetChildren(Id).Select(RetrieveChild).Where(i => i != null);
  777. }
  778. /// <summary>
  779. /// Retrieves the child.
  780. /// </summary>
  781. /// <param name="child">The child.</param>
  782. /// <returns>BaseItem.</returns>
  783. private BaseItem RetrieveChild(Guid child)
  784. {
  785. var item = LibraryManager.RetrieveItem(child);
  786. if (item != null)
  787. {
  788. if (item is IByReferenceItem)
  789. {
  790. return LibraryManager.GetOrAddByReferenceItem(item);
  791. }
  792. item.Parent = this;
  793. }
  794. return item;
  795. }
  796. /// <summary>
  797. /// Gets allowed children of an item
  798. /// </summary>
  799. /// <param name="user">The user.</param>
  800. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  801. /// <param name="indexBy">The index by.</param>
  802. /// <returns>IEnumerable{BaseItem}.</returns>
  803. /// <exception cref="System.ArgumentNullException"></exception>
  804. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren, string indexBy = null)
  805. {
  806. if (user == null)
  807. {
  808. throw new ArgumentNullException();
  809. }
  810. //the true root should return our users root folder children
  811. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren, indexBy);
  812. IEnumerable<BaseItem> result = null;
  813. if (!string.IsNullOrEmpty(indexBy))
  814. {
  815. result = GetIndexedChildren(user, indexBy);
  816. }
  817. if (result != null)
  818. {
  819. return result;
  820. }
  821. var children = Children;
  822. if (includeLinkedChildren)
  823. {
  824. children = children.Concat(GetLinkedChildren());
  825. }
  826. // If indexed is false or the indexing function is null
  827. return children.Where(c => c.IsVisible(user));
  828. }
  829. /// <summary>
  830. /// Gets allowed recursive children of an item
  831. /// </summary>
  832. /// <param name="user">The user.</param>
  833. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  834. /// <returns>IEnumerable{BaseItem}.</returns>
  835. /// <exception cref="System.ArgumentNullException"></exception>
  836. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = false)
  837. {
  838. if (user == null)
  839. {
  840. throw new ArgumentNullException();
  841. }
  842. foreach (var item in GetChildren(user, includeLinkedChildren))
  843. {
  844. yield return item;
  845. var subFolder = item as Folder;
  846. if (subFolder != null)
  847. {
  848. foreach (var subitem in subFolder.GetRecursiveChildren(user, includeLinkedChildren))
  849. {
  850. yield return subitem;
  851. }
  852. }
  853. }
  854. }
  855. /// <summary>
  856. /// Gets the linked children.
  857. /// </summary>
  858. /// <returns>IEnumerable{BaseItem}.</returns>
  859. public IEnumerable<BaseItem> GetLinkedChildren()
  860. {
  861. return LinkedChildren
  862. .Select(GetLinkedChild)
  863. .Where(i => i != null);
  864. }
  865. /// <summary>
  866. /// Gets the linked child.
  867. /// </summary>
  868. /// <param name="info">The info.</param>
  869. /// <returns>BaseItem.</returns>
  870. private BaseItem GetLinkedChild(LinkedChild info)
  871. {
  872. var item = LibraryManager.RootFolder.FindByPath(info.Path);
  873. if (item == null)
  874. {
  875. Logger.Warn("Unable to find linked item at {0}", info.Path);
  876. }
  877. return item;
  878. }
  879. public override async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  880. {
  881. var changed = await base.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs).ConfigureAwait(false);
  882. return changed || (SupportsShortcutChildren && LocationType == LocationType.FileSystem && RefreshLinkedChildren());
  883. }
  884. /// <summary>
  885. /// Refreshes the linked children.
  886. /// </summary>
  887. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  888. private bool RefreshLinkedChildren()
  889. {
  890. ItemResolveArgs resolveArgs;
  891. try
  892. {
  893. resolveArgs = ResolveArgs;
  894. if (!resolveArgs.IsDirectory)
  895. {
  896. return false;
  897. }
  898. }
  899. catch (IOException ex)
  900. {
  901. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  902. return false;
  903. }
  904. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  905. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  906. var newShortcutLinks = resolveArgs.FileSystemChildren
  907. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  908. .Select(i =>
  909. {
  910. try
  911. {
  912. return new LinkedChild
  913. {
  914. Path = FileSystem.ResolveShortcut(i.FullName),
  915. Type = LinkedChildType.Shortcut
  916. };
  917. }
  918. catch (IOException ex)
  919. {
  920. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  921. return null;
  922. }
  923. })
  924. .Where(i => i != null)
  925. .ToList();
  926. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks))
  927. {
  928. Logger.Info("Shortcut links have changed for {0}", Path);
  929. newShortcutLinks.AddRange(currentManualLinks);
  930. LinkedChildren = newShortcutLinks;
  931. return true;
  932. }
  933. return false;
  934. }
  935. /// <summary>
  936. /// Folders need to validate and refresh
  937. /// </summary>
  938. /// <returns>Task.</returns>
  939. public override async Task ChangedExternally()
  940. {
  941. await base.ChangedExternally().ConfigureAwait(false);
  942. var progress = new Progress<double>();
  943. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  944. }
  945. /// <summary>
  946. /// Marks the item as either played or unplayed
  947. /// </summary>
  948. /// <param name="user">The user.</param>
  949. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  950. /// <param name="userManager">The user manager.</param>
  951. /// <returns>Task.</returns>
  952. public override async Task SetPlayedStatus(User user, bool wasPlayed, IUserDataRepository userManager)
  953. {
  954. // Sweep through recursively and update status
  955. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder).Select(c => c.SetPlayedStatus(user, wasPlayed, userManager));
  956. await Task.WhenAll(tasks).ConfigureAwait(false);
  957. }
  958. /// <summary>
  959. /// Finds an item by path, recursively
  960. /// </summary>
  961. /// <param name="path">The path.</param>
  962. /// <returns>BaseItem.</returns>
  963. /// <exception cref="System.ArgumentNullException"></exception>
  964. public BaseItem FindByPath(string path)
  965. {
  966. if (string.IsNullOrEmpty(path))
  967. {
  968. throw new ArgumentNullException();
  969. }
  970. try
  971. {
  972. if (ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  973. {
  974. return this;
  975. }
  976. }
  977. catch (IOException ex)
  978. {
  979. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  980. }
  981. //this should be functionally equivilent to what was here since it is IEnum and works on a thread-safe copy
  982. return RecursiveChildren.FirstOrDefault(i =>
  983. {
  984. try
  985. {
  986. return i.ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase);
  987. }
  988. catch (IOException ex)
  989. {
  990. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  991. return false;
  992. }
  993. });
  994. }
  995. }
  996. }