Folder.cs 49 KB

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