Folder.cs 44 KB

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