Folder.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  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
  495. {
  496. foreach (var item in Children)
  497. {
  498. yield return item;
  499. if (item.IsFolder)
  500. {
  501. var subFolder = (Folder)item;
  502. foreach (var subitem in subFolder.RecursiveChildren)
  503. {
  504. yield return subitem;
  505. }
  506. }
  507. }
  508. }
  509. }
  510. private List<BaseItem> LoadChildrenInternal()
  511. {
  512. return LoadChildren().ToList();
  513. }
  514. /// <summary>
  515. /// Loads our children. Validation will occur externally.
  516. /// We want this sychronous.
  517. /// </summary>
  518. protected virtual IEnumerable<BaseItem> LoadChildren()
  519. {
  520. //just load our children from the repo - the library will be validated and maintained in other processes
  521. return GetCachedChildren();
  522. }
  523. /// <summary>
  524. /// Gets or sets the current validation cancellation token source.
  525. /// </summary>
  526. /// <value>The current validation cancellation token source.</value>
  527. private CancellationTokenSource CurrentValidationCancellationTokenSource { get; set; }
  528. /// <summary>
  529. /// Validates that the children of the folder still exist
  530. /// </summary>
  531. /// <param name="progress">The progress.</param>
  532. /// <param name="cancellationToken">The cancellation token.</param>
  533. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  534. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  535. /// <returns>Task.</returns>
  536. public async Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken, bool? recursive = null, bool forceRefreshMetadata = false)
  537. {
  538. cancellationToken.ThrowIfCancellationRequested();
  539. // Cancel the current validation, if any
  540. if (CurrentValidationCancellationTokenSource != null)
  541. {
  542. CurrentValidationCancellationTokenSource.Cancel();
  543. }
  544. // Create an inner cancellation token. This can cancel all validations from this level on down,
  545. // but nothing above this
  546. var innerCancellationTokenSource = new CancellationTokenSource();
  547. try
  548. {
  549. CurrentValidationCancellationTokenSource = innerCancellationTokenSource;
  550. var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(innerCancellationTokenSource.Token, cancellationToken);
  551. await ValidateChildrenInternal(progress, linkedCancellationTokenSource.Token, recursive, forceRefreshMetadata).ConfigureAwait(false);
  552. }
  553. catch (OperationCanceledException ex)
  554. {
  555. Logger.Info("ValidateChildren cancelled for " + Name);
  556. // If the outer cancelletion token in the cause for the cancellation, throw it
  557. if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken)
  558. {
  559. throw;
  560. }
  561. }
  562. finally
  563. {
  564. // Null out the token source
  565. if (CurrentValidationCancellationTokenSource == innerCancellationTokenSource)
  566. {
  567. CurrentValidationCancellationTokenSource = null;
  568. }
  569. innerCancellationTokenSource.Dispose();
  570. }
  571. }
  572. /// <summary>
  573. /// Compare our current children (presumably just read from the repo) with the current state of the file system and adjust for any changes
  574. /// ***Currently does not contain logic to maintain items that are unavailable in the file system***
  575. /// </summary>
  576. /// <param name="progress">The progress.</param>
  577. /// <param name="cancellationToken">The cancellation token.</param>
  578. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  579. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  580. /// <returns>Task.</returns>
  581. protected async virtual Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool? recursive = null, bool forceRefreshMetadata = false)
  582. {
  583. var locationType = LocationType;
  584. // Nothing to do here
  585. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  586. {
  587. return;
  588. }
  589. cancellationToken.ThrowIfCancellationRequested();
  590. IEnumerable<BaseItem> nonCachedChildren;
  591. try
  592. {
  593. nonCachedChildren = GetNonCachedChildren();
  594. }
  595. catch (IOException ex)
  596. {
  597. nonCachedChildren = new BaseItem[] { };
  598. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  599. }
  600. if (nonCachedChildren == null) return; //nothing to validate
  601. progress.Report(5);
  602. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  603. var currentChildren = ActualChildren.ToDictionary(i => i.Id);
  604. //create a list for our validated children
  605. var validChildren = new ConcurrentBag<Tuple<BaseItem, bool>>();
  606. var newItems = new ConcurrentBag<BaseItem>();
  607. cancellationToken.ThrowIfCancellationRequested();
  608. var options = new ParallelOptions
  609. {
  610. MaxDegreeOfParallelism = 10
  611. };
  612. Parallel.ForEach(nonCachedChildren, options, child =>
  613. {
  614. BaseItem currentChild;
  615. if (currentChildren.TryGetValue(child.Id, out currentChild))
  616. {
  617. currentChild.ResetResolveArgs(child.ResolveArgs);
  618. //existing item - check if it has changed
  619. if (currentChild.HasChanged(child))
  620. {
  621. EntityResolutionHelper.EnsureDates(currentChild, child.ResolveArgs, false);
  622. validChildren.Add(new Tuple<BaseItem, bool>(currentChild, true));
  623. }
  624. else
  625. {
  626. validChildren.Add(new Tuple<BaseItem, bool>(currentChild, false));
  627. }
  628. currentChild.IsOffline = false;
  629. }
  630. else
  631. {
  632. //brand new item - needs to be added
  633. newItems.Add(child);
  634. validChildren.Add(new Tuple<BaseItem, bool>(child, true));
  635. }
  636. });
  637. // If any items were added or removed....
  638. if (!newItems.IsEmpty || currentChildren.Count != validChildren.Count)
  639. {
  640. var newChildren = validChildren.Select(c => c.Item1).ToList();
  641. //that's all the new and changed ones - now see if there are any that are missing
  642. var itemsRemoved = currentChildren.Values.Except(newChildren).ToList();
  643. var actualRemovals = new List<BaseItem>();
  644. foreach (var item in itemsRemoved)
  645. {
  646. if (IsRootPathAvailable(item.Path))
  647. {
  648. item.IsOffline = false;
  649. actualRemovals.Add(item);
  650. }
  651. else
  652. {
  653. item.IsOffline = true;
  654. validChildren.Add(new Tuple<BaseItem, bool>(item, false));
  655. }
  656. }
  657. if (actualRemovals.Count > 0)
  658. {
  659. RemoveChildrenInternal(actualRemovals);
  660. foreach (var item in actualRemovals)
  661. {
  662. LibraryManager.ReportItemRemoved(item);
  663. }
  664. }
  665. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  666. AddChildrenInternal(newItems);
  667. await ItemRepository.SaveChildren(Id, _children.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  668. //force the indexes to rebuild next time
  669. if (IndexCache != null)
  670. {
  671. IndexCache.Clear();
  672. }
  673. }
  674. progress.Report(10);
  675. cancellationToken.ThrowIfCancellationRequested();
  676. await RefreshChildren(validChildren, progress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  677. progress.Report(100);
  678. }
  679. /// <summary>
  680. /// Refreshes the children.
  681. /// </summary>
  682. /// <param name="children">The children.</param>
  683. /// <param name="progress">The progress.</param>
  684. /// <param name="cancellationToken">The cancellation token.</param>
  685. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  686. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  687. /// <returns>Task.</returns>
  688. private async Task RefreshChildren(IEnumerable<Tuple<BaseItem, bool>> children, IProgress<double> progress, CancellationToken cancellationToken, bool? recursive, bool forceRefreshMetadata = false)
  689. {
  690. var list = children.ToList();
  691. var percentages = new Dictionary<Guid, double>(list.Count);
  692. var tasks = new List<Task>();
  693. foreach (var tuple in list)
  694. {
  695. if (tasks.Count > 5)
  696. {
  697. await Task.WhenAll(tasks).ConfigureAwait(false);
  698. }
  699. Tuple<BaseItem, bool> currentTuple = tuple;
  700. tasks.Add(Task.Run(async () =>
  701. {
  702. cancellationToken.ThrowIfCancellationRequested();
  703. var child = currentTuple.Item1;
  704. //refresh it
  705. await child.RefreshMetadata(cancellationToken, forceSave: currentTuple.Item2, forceRefresh: forceRefreshMetadata, resetResolveArgs: false).ConfigureAwait(false);
  706. // Refresh children if a folder and the item changed or recursive is set to true
  707. var refreshChildren = child.IsFolder && (currentTuple.Item2 || (recursive.HasValue && recursive.Value));
  708. if (refreshChildren)
  709. {
  710. // Don't refresh children if explicitly set to false
  711. if (recursive.HasValue && recursive.Value == false)
  712. {
  713. refreshChildren = false;
  714. }
  715. }
  716. if (refreshChildren)
  717. {
  718. cancellationToken.ThrowIfCancellationRequested();
  719. var innerProgress = new ActionableProgress<double>();
  720. innerProgress.RegisterAction(p =>
  721. {
  722. lock (percentages)
  723. {
  724. percentages[child.Id] = p / 100;
  725. var percent = percentages.Values.Sum();
  726. percent /= list.Count;
  727. progress.Report((90 * percent) + 10);
  728. }
  729. });
  730. await ((Folder)child).ValidateChildren(innerProgress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  731. // Some folder providers are unable to refresh until children have been refreshed.
  732. await child.RefreshMetadata(cancellationToken, resetResolveArgs: false).ConfigureAwait(false);
  733. }
  734. else
  735. {
  736. lock (percentages)
  737. {
  738. percentages[child.Id] = 1;
  739. var percent = percentages.Values.Sum();
  740. percent /= list.Count;
  741. progress.Report((90 * percent) + 10);
  742. }
  743. }
  744. }));
  745. }
  746. cancellationToken.ThrowIfCancellationRequested();
  747. await Task.WhenAll(tasks).ConfigureAwait(false);
  748. }
  749. /// <summary>
  750. /// Determines if a path's root is available or not
  751. /// </summary>
  752. /// <param name="path"></param>
  753. /// <returns></returns>
  754. private bool IsRootPathAvailable(string path)
  755. {
  756. if (File.Exists(path))
  757. {
  758. return true;
  759. }
  760. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  761. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  762. {
  763. if (Directory.Exists(path))
  764. {
  765. return true;
  766. }
  767. path = System.IO.Path.GetDirectoryName(path);
  768. }
  769. return false;
  770. }
  771. /// <summary>
  772. /// Get the children of this folder from the actual file system
  773. /// </summary>
  774. /// <returns>IEnumerable{BaseItem}.</returns>
  775. protected virtual IEnumerable<BaseItem> GetNonCachedChildren()
  776. {
  777. if (ResolveArgs == null || ResolveArgs.FileSystemDictionary == null)
  778. {
  779. Logger.Error("Null for {0}", Path);
  780. }
  781. return LibraryManager.ResolvePaths<BaseItem>(ResolveArgs.FileSystemChildren, this);
  782. }
  783. /// <summary>
  784. /// Get our children from the repo - stubbed for now
  785. /// </summary>
  786. /// <returns>IEnumerable{BaseItem}.</returns>
  787. protected IEnumerable<BaseItem> GetCachedChildren()
  788. {
  789. return ItemRepository.GetChildren(Id).Select(RetrieveChild).Where(i => i != null);
  790. }
  791. /// <summary>
  792. /// Retrieves the child.
  793. /// </summary>
  794. /// <param name="child">The child.</param>
  795. /// <returns>BaseItem.</returns>
  796. private BaseItem RetrieveChild(Guid child)
  797. {
  798. var item = LibraryManager.RetrieveItem(child);
  799. if (item != null)
  800. {
  801. if (item is IByReferenceItem)
  802. {
  803. return LibraryManager.GetOrAddByReferenceItem(item);
  804. }
  805. item.Parent = this;
  806. }
  807. return item;
  808. }
  809. /// <summary>
  810. /// Gets allowed children of an item
  811. /// </summary>
  812. /// <param name="user">The user.</param>
  813. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  814. /// <param name="indexBy">The index by.</param>
  815. /// <returns>IEnumerable{BaseItem}.</returns>
  816. /// <exception cref="System.ArgumentNullException"></exception>
  817. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren, string indexBy = null)
  818. {
  819. if (user == null)
  820. {
  821. throw new ArgumentNullException();
  822. }
  823. //the true root should return our users root folder children
  824. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren, indexBy);
  825. IEnumerable<BaseItem> result = null;
  826. if (!string.IsNullOrEmpty(indexBy))
  827. {
  828. result = GetIndexedChildren(user, indexBy);
  829. }
  830. if (result != null)
  831. {
  832. return result;
  833. }
  834. return GetChildrenList(user, includeLinkedChildren);
  835. }
  836. /// <summary>
  837. /// Gets the children list.
  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>List{BaseItem}.</returns>
  842. private List<BaseItem> GetChildrenList(User user, bool includeLinkedChildren)
  843. {
  844. var list = new List<BaseItem>();
  845. foreach (var child in Children)
  846. {
  847. if (child.IsVisible(user))
  848. {
  849. list.Add(child);
  850. }
  851. }
  852. if (includeLinkedChildren)
  853. {
  854. foreach (var child in GetLinkedChildren())
  855. {
  856. if (child.IsVisible(user))
  857. {
  858. list.Add(child);
  859. }
  860. }
  861. }
  862. return list;
  863. }
  864. /// <summary>
  865. /// Gets allowed recursive children of an item
  866. /// </summary>
  867. /// <param name="user">The user.</param>
  868. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  869. /// <returns>IEnumerable{BaseItem}.</returns>
  870. /// <exception cref="System.ArgumentNullException"></exception>
  871. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  872. {
  873. if (user == null)
  874. {
  875. throw new ArgumentNullException();
  876. }
  877. var initialCount = _children.Count;
  878. var list = new List<BaseItem>(initialCount);
  879. AddRecursiveChildrenInternal(user, includeLinkedChildren, list);
  880. if (includeLinkedChildren)
  881. {
  882. list = list.Distinct().ToList();
  883. }
  884. return list;
  885. }
  886. /// <summary>
  887. /// Adds the recursive children internal.
  888. /// </summary>
  889. /// <param name="user">The user.</param>
  890. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  891. /// <param name="list">The list.</param>
  892. private void AddRecursiveChildrenInternal(User user, bool includeLinkedChildren, List<BaseItem> list)
  893. {
  894. foreach (var item in GetChildrenList(user, includeLinkedChildren))
  895. {
  896. list.Add(item);
  897. var subFolder = item as Folder;
  898. if (subFolder != null)
  899. {
  900. subFolder.AddRecursiveChildrenInternal(user, includeLinkedChildren, list);
  901. }
  902. }
  903. }
  904. /// <summary>
  905. /// Gets the linked children.
  906. /// </summary>
  907. /// <returns>IEnumerable{BaseItem}.</returns>
  908. public IEnumerable<BaseItem> GetLinkedChildren()
  909. {
  910. return LinkedChildren
  911. .Select(GetLinkedChild)
  912. .Where(i => i != null);
  913. }
  914. /// <summary>
  915. /// Gets the linked child.
  916. /// </summary>
  917. /// <param name="info">The info.</param>
  918. /// <returns>BaseItem.</returns>
  919. private BaseItem GetLinkedChild(LinkedChild info)
  920. {
  921. if (string.IsNullOrEmpty(info.Path))
  922. {
  923. throw new ArgumentException("Encountered linked child with empty path.");
  924. }
  925. var item = LibraryManager.RootFolder.FindByPath(info.Path);
  926. if (item == null)
  927. {
  928. Logger.Warn("Unable to find linked item at {0}", info.Path);
  929. }
  930. return item;
  931. }
  932. public override async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  933. {
  934. var changed = await base.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs).ConfigureAwait(false);
  935. return changed || (SupportsShortcutChildren && LocationType == LocationType.FileSystem && RefreshLinkedChildren());
  936. }
  937. /// <summary>
  938. /// Refreshes the linked children.
  939. /// </summary>
  940. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  941. private bool RefreshLinkedChildren()
  942. {
  943. ItemResolveArgs resolveArgs;
  944. try
  945. {
  946. resolveArgs = ResolveArgs;
  947. if (!resolveArgs.IsDirectory)
  948. {
  949. return false;
  950. }
  951. }
  952. catch (IOException ex)
  953. {
  954. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  955. return false;
  956. }
  957. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  958. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  959. var newShortcutLinks = resolveArgs.FileSystemChildren
  960. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  961. .Select(i =>
  962. {
  963. try
  964. {
  965. Logger.Debug("Found shortcut at {0}", i.FullName);
  966. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  967. if (!string.IsNullOrEmpty(resolvedPath))
  968. {
  969. return new LinkedChild
  970. {
  971. Path = resolvedPath,
  972. Type = LinkedChildType.Shortcut
  973. };
  974. }
  975. Logger.Error("Error resolving shortcut {0}", i.FullName);
  976. return null;
  977. }
  978. catch (IOException ex)
  979. {
  980. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  981. return null;
  982. }
  983. })
  984. .Where(i => i != null)
  985. .ToList();
  986. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks))
  987. {
  988. Logger.Info("Shortcut links have changed for {0}", Path);
  989. newShortcutLinks.AddRange(currentManualLinks);
  990. LinkedChildren = newShortcutLinks;
  991. return true;
  992. }
  993. return false;
  994. }
  995. /// <summary>
  996. /// Folders need to validate and refresh
  997. /// </summary>
  998. /// <returns>Task.</returns>
  999. public override async Task ChangedExternally()
  1000. {
  1001. await base.ChangedExternally().ConfigureAwait(false);
  1002. var progress = new Progress<double>();
  1003. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  1004. }
  1005. /// <summary>
  1006. /// Marks the played.
  1007. /// </summary>
  1008. /// <param name="user">The user.</param>
  1009. /// <param name="datePlayed">The date played.</param>
  1010. /// <param name="userManager">The user manager.</param>
  1011. /// <returns>Task.</returns>
  1012. public override async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataRepository userManager)
  1013. {
  1014. // Sweep through recursively and update status
  1015. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder).Select(c => c.MarkPlayed(user, datePlayed, userManager));
  1016. await Task.WhenAll(tasks).ConfigureAwait(false);
  1017. }
  1018. /// <summary>
  1019. /// Marks the unplayed.
  1020. /// </summary>
  1021. /// <param name="user">The user.</param>
  1022. /// <param name="userManager">The user manager.</param>
  1023. /// <returns>Task.</returns>
  1024. public override async Task MarkUnplayed(User user, IUserDataRepository userManager)
  1025. {
  1026. // Sweep through recursively and update status
  1027. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder).Select(c => c.MarkUnplayed(user, userManager));
  1028. await Task.WhenAll(tasks).ConfigureAwait(false);
  1029. }
  1030. /// <summary>
  1031. /// Finds an item by path, recursively
  1032. /// </summary>
  1033. /// <param name="path">The path.</param>
  1034. /// <returns>BaseItem.</returns>
  1035. /// <exception cref="System.ArgumentNullException"></exception>
  1036. public BaseItem FindByPath(string path)
  1037. {
  1038. if (string.IsNullOrEmpty(path))
  1039. {
  1040. throw new ArgumentNullException();
  1041. }
  1042. try
  1043. {
  1044. if (ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1045. {
  1046. return this;
  1047. }
  1048. }
  1049. catch (IOException ex)
  1050. {
  1051. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1052. }
  1053. //this should be functionally equivilent to what was here since it is IEnum and works on a thread-safe copy
  1054. return RecursiveChildren.FirstOrDefault(i =>
  1055. {
  1056. try
  1057. {
  1058. return i.ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase);
  1059. }
  1060. catch (IOException ex)
  1061. {
  1062. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1063. return false;
  1064. }
  1065. });
  1066. }
  1067. }
  1068. }