Folder.cs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  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);
  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);
  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);
  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(StringComparer.OrdinalIgnoreCase)
  308. .Select(i =>
  309. {
  310. try
  311. {
  312. return LibraryManager.GetGenre(i);
  313. }
  314. catch (Exception ex)
  315. {
  316. Logger.ErrorException("Error getting genre {0}", ex, i);
  317. return null;
  318. }
  319. })
  320. .Where(i => i != null)
  321. .Select(genre => new IndexFolder(this, genre, candidates.Where(i => i.AllGenres.Any(g => g.Equals(genre.Name, StringComparison.OrdinalIgnoreCase))), indexName)
  322. );
  323. }
  324. }
  325. /// <summary>
  326. /// Gets the index by year.
  327. /// </summary>
  328. /// <param name="user">The user.</param>
  329. /// <returns>IEnumerable{BaseItem}.</returns>
  330. protected IEnumerable<BaseItem> GetIndexByYear(User user)
  331. {
  332. // Even though this implementation means multiple iterations over the target list - it allows us to defer
  333. // the retrieval of the individual children for each index value until they are requested.
  334. using (new Profiler("Production Year Index Build for " + Name, Logger))
  335. {
  336. var indexName = LocalizedStrings.Instance.GetString("YearDispPref");
  337. //we need a copy of this so we don't double-recurse
  338. var candidates = GetRecursiveChildren(user).Where(i => i.IncludeInIndex && i.ProductionYear.HasValue).ToList();
  339. return candidates.AsParallel().Select(i => i.ProductionYear.Value)
  340. .Distinct()
  341. .Select(i =>
  342. {
  343. try
  344. {
  345. return LibraryManager.GetYear(i);
  346. }
  347. catch (IOException ex)
  348. {
  349. Logger.ErrorException("Error getting year {0}", ex, i);
  350. return null;
  351. }
  352. catch (AggregateException ex)
  353. {
  354. Logger.ErrorException("Error getting year {0}", ex, i);
  355. return null;
  356. }
  357. })
  358. .Where(i => i != null)
  359. .Select(ndx => new IndexFolder(this, ndx, candidates.Where(i => i.ProductionYear == int.Parse(ndx.Name)), indexName));
  360. }
  361. }
  362. /// <summary>
  363. /// Returns the indexed children for this user from the cache. Caches them if not already there.
  364. /// </summary>
  365. /// <param name="user">The user.</param>
  366. /// <param name="indexBy">The index by.</param>
  367. /// <returns>IEnumerable{BaseItem}.</returns>
  368. private IEnumerable<BaseItem> GetIndexedChildren(User user, string indexBy)
  369. {
  370. List<BaseItem> result;
  371. var cacheKey = user.Name + indexBy;
  372. IndexCache.TryGetValue(cacheKey, out result);
  373. if (result == null)
  374. {
  375. //not cached - cache it
  376. Func<User, IEnumerable<BaseItem>> indexing;
  377. IndexByOptions.TryGetValue(indexBy, out indexing);
  378. result = BuildIndex(indexBy, indexing, user);
  379. }
  380. return result;
  381. }
  382. /// <summary>
  383. /// Get the list of indexy by choices for this folder (localized).
  384. /// </summary>
  385. /// <value>The index by option strings.</value>
  386. [IgnoreDataMember]
  387. public IEnumerable<string> IndexByOptionStrings
  388. {
  389. get { return IndexByOptions.Keys; }
  390. }
  391. /// <summary>
  392. /// The index cache
  393. /// </summary>
  394. protected ConcurrentDictionary<string, List<BaseItem>> IndexCache = new ConcurrentDictionary<string, List<BaseItem>>(StringComparer.OrdinalIgnoreCase);
  395. /// <summary>
  396. /// Builds the index.
  397. /// </summary>
  398. /// <param name="indexKey">The index key.</param>
  399. /// <param name="indexFunction">The index function.</param>
  400. /// <param name="user">The user.</param>
  401. /// <returns>List{BaseItem}.</returns>
  402. protected virtual List<BaseItem> BuildIndex(string indexKey, Func<User, IEnumerable<BaseItem>> indexFunction, User user)
  403. {
  404. return indexFunction != null
  405. ? IndexCache[user.Name + indexKey] = indexFunction(user).ToList()
  406. : null;
  407. }
  408. #endregion
  409. /// <summary>
  410. /// The children
  411. /// </summary>
  412. private ConcurrentDictionary<Guid, BaseItem> _children;
  413. /// <summary>
  414. /// The _children initialized
  415. /// </summary>
  416. private bool _childrenInitialized;
  417. /// <summary>
  418. /// The _children sync lock
  419. /// </summary>
  420. private object _childrenSyncLock = new object();
  421. /// <summary>
  422. /// Gets or sets the actual children.
  423. /// </summary>
  424. /// <value>The actual children.</value>
  425. protected virtual ConcurrentDictionary<Guid, BaseItem> ActualChildren
  426. {
  427. get
  428. {
  429. LazyInitializer.EnsureInitialized(ref _children, ref _childrenInitialized, ref _childrenSyncLock, LoadChildren);
  430. return _children;
  431. }
  432. private set
  433. {
  434. _children = value;
  435. if (value == null)
  436. {
  437. _childrenInitialized = false;
  438. }
  439. }
  440. }
  441. /// <summary>
  442. /// thread-safe access to the actual children of this folder - without regard to user
  443. /// </summary>
  444. /// <value>The children.</value>
  445. [IgnoreDataMember]
  446. public IEnumerable<BaseItem> Children
  447. {
  448. get
  449. {
  450. return ActualChildren.Values.ToArray();
  451. }
  452. }
  453. /// <summary>
  454. /// thread-safe access to all recursive children of this folder - without regard to user
  455. /// </summary>
  456. /// <value>The recursive children.</value>
  457. [IgnoreDataMember]
  458. public IEnumerable<BaseItem> RecursiveChildren
  459. {
  460. get
  461. {
  462. foreach (var item in Children)
  463. {
  464. yield return item;
  465. if (item.IsFolder)
  466. {
  467. var subFolder = (Folder)item;
  468. foreach (var subitem in subFolder.RecursiveChildren)
  469. {
  470. yield return subitem;
  471. }
  472. }
  473. }
  474. }
  475. }
  476. /// <summary>
  477. /// Loads our children. Validation will occur externally.
  478. /// We want this sychronous.
  479. /// </summary>
  480. /// <returns>ConcurrentBag{BaseItem}.</returns>
  481. protected virtual ConcurrentDictionary<Guid, BaseItem> LoadChildren()
  482. {
  483. //just load our children from the repo - the library will be validated and maintained in other processes
  484. return new ConcurrentDictionary<Guid, BaseItem>(GetCachedChildren().ToDictionary(i => i.Id));
  485. }
  486. /// <summary>
  487. /// Gets or sets the current validation cancellation token source.
  488. /// </summary>
  489. /// <value>The current validation cancellation token source.</value>
  490. private CancellationTokenSource CurrentValidationCancellationTokenSource { get; set; }
  491. /// <summary>
  492. /// Validates that the children of the folder still exist
  493. /// </summary>
  494. /// <param name="progress">The progress.</param>
  495. /// <param name="cancellationToken">The cancellation token.</param>
  496. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  497. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  498. /// <returns>Task.</returns>
  499. public async Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken, bool? recursive = null, bool forceRefreshMetadata = false)
  500. {
  501. cancellationToken.ThrowIfCancellationRequested();
  502. // Cancel the current validation, if any
  503. if (CurrentValidationCancellationTokenSource != null)
  504. {
  505. CurrentValidationCancellationTokenSource.Cancel();
  506. }
  507. // Create an inner cancellation token. This can cancel all validations from this level on down,
  508. // but nothing above this
  509. var innerCancellationTokenSource = new CancellationTokenSource();
  510. try
  511. {
  512. CurrentValidationCancellationTokenSource = innerCancellationTokenSource;
  513. var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(innerCancellationTokenSource.Token, cancellationToken);
  514. await ValidateChildrenInternal(progress, linkedCancellationTokenSource.Token, recursive, forceRefreshMetadata).ConfigureAwait(false);
  515. }
  516. catch (OperationCanceledException ex)
  517. {
  518. Logger.Info("ValidateChildren cancelled for " + Name);
  519. // If the outer cancelletion token in the cause for the cancellation, throw it
  520. if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken)
  521. {
  522. throw;
  523. }
  524. }
  525. finally
  526. {
  527. // Null out the token source
  528. if (CurrentValidationCancellationTokenSource == innerCancellationTokenSource)
  529. {
  530. CurrentValidationCancellationTokenSource = null;
  531. }
  532. innerCancellationTokenSource.Dispose();
  533. }
  534. }
  535. /// <summary>
  536. /// Compare our current children (presumably just read from the repo) with the current state of the file system and adjust for any changes
  537. /// ***Currently does not contain logic to maintain items that are unavailable in the file system***
  538. /// </summary>
  539. /// <param name="progress">The progress.</param>
  540. /// <param name="cancellationToken">The cancellation token.</param>
  541. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  542. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  543. /// <returns>Task.</returns>
  544. protected async virtual Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool? recursive = null, bool forceRefreshMetadata = false)
  545. {
  546. var locationType = LocationType;
  547. // Nothing to do here
  548. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  549. {
  550. return;
  551. }
  552. cancellationToken.ThrowIfCancellationRequested();
  553. IEnumerable<BaseItem> nonCachedChildren;
  554. try
  555. {
  556. nonCachedChildren = GetNonCachedChildren();
  557. }
  558. catch (IOException ex)
  559. {
  560. nonCachedChildren = new BaseItem[] { };
  561. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  562. }
  563. if (nonCachedChildren == null) return; //nothing to validate
  564. progress.Report(5);
  565. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  566. var currentChildren = ActualChildren;
  567. //create a list for our validated children
  568. var validChildren = new ConcurrentBag<Tuple<BaseItem, bool>>();
  569. var newItems = new ConcurrentBag<BaseItem>();
  570. cancellationToken.ThrowIfCancellationRequested();
  571. var options = new ParallelOptions
  572. {
  573. MaxDegreeOfParallelism = 20
  574. };
  575. Parallel.ForEach(nonCachedChildren, options, child =>
  576. {
  577. BaseItem currentChild;
  578. if (currentChildren.TryGetValue(child.Id, out currentChild))
  579. {
  580. currentChild.ResolveArgs = child.ResolveArgs;
  581. //existing item - check if it has changed
  582. if (currentChild.HasChanged(child))
  583. {
  584. EntityResolutionHelper.EnsureDates(currentChild, child.ResolveArgs, false);
  585. validChildren.Add(new Tuple<BaseItem, bool>(currentChild, true));
  586. }
  587. else
  588. {
  589. validChildren.Add(new Tuple<BaseItem, bool>(currentChild, false));
  590. }
  591. currentChild.IsOffline = false;
  592. }
  593. else
  594. {
  595. //brand new item - needs to be added
  596. newItems.Add(child);
  597. validChildren.Add(new Tuple<BaseItem, bool>(child, true));
  598. }
  599. });
  600. // If any items were added or removed....
  601. if (!newItems.IsEmpty || currentChildren.Count != validChildren.Count)
  602. {
  603. var newChildren = validChildren.Select(c => c.Item1).ToList();
  604. //that's all the new and changed ones - now see if there are any that are missing
  605. var itemsRemoved = currentChildren.Values.Except(newChildren).ToList();
  606. foreach (var item in itemsRemoved)
  607. {
  608. if (IsRootPathAvailable(item.Path))
  609. {
  610. item.IsOffline = false;
  611. BaseItem removed;
  612. if (!_children.TryRemove(item.Id, out removed))
  613. {
  614. Logger.Error("Failed to remove {0}", item.Name);
  615. }
  616. else
  617. {
  618. LibraryManager.ReportItemRemoved(item);
  619. }
  620. }
  621. else
  622. {
  623. item.IsOffline = true;
  624. validChildren.Add(new Tuple<BaseItem, bool>(item, false));
  625. }
  626. }
  627. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  628. foreach (var item in newItems)
  629. {
  630. if (!_children.TryAdd(item.Id, item))
  631. {
  632. Logger.Error("Failed to add {0}", item.Name);
  633. }
  634. else
  635. {
  636. Logger.Debug("** " + item.Name + " Added to library.");
  637. }
  638. }
  639. await ItemRepository.SaveChildren(Id, _children.Values.ToList().Select(i => i.Id), cancellationToken).ConfigureAwait(false);
  640. //force the indexes to rebuild next time
  641. IndexCache.Clear();
  642. }
  643. progress.Report(10);
  644. cancellationToken.ThrowIfCancellationRequested();
  645. await RefreshChildren(validChildren, progress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  646. progress.Report(100);
  647. }
  648. /// <summary>
  649. /// Refreshes the children.
  650. /// </summary>
  651. /// <param name="children">The children.</param>
  652. /// <param name="progress">The progress.</param>
  653. /// <param name="cancellationToken">The cancellation token.</param>
  654. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  655. /// <param name="forceRefreshMetadata">if set to <c>true</c> [force refresh metadata].</param>
  656. /// <returns>Task.</returns>
  657. private async Task RefreshChildren(IEnumerable<Tuple<BaseItem, bool>> children, IProgress<double> progress, CancellationToken cancellationToken, bool? recursive, bool forceRefreshMetadata = false)
  658. {
  659. var list = children.ToList();
  660. var percentages = new Dictionary<Guid, double>(list.Count);
  661. var tasks = new List<Task>();
  662. foreach (var tuple in list)
  663. {
  664. if (tasks.Count > 8)
  665. {
  666. await Task.WhenAll(tasks).ConfigureAwait(false);
  667. }
  668. Tuple<BaseItem, bool> currentTuple = tuple;
  669. tasks.Add(Task.Run(async () =>
  670. {
  671. cancellationToken.ThrowIfCancellationRequested();
  672. var child = currentTuple.Item1;
  673. //refresh it
  674. await child.RefreshMetadata(cancellationToken, forceSave: currentTuple.Item2, forceRefresh: forceRefreshMetadata, resetResolveArgs: false).ConfigureAwait(false);
  675. // Refresh children if a folder and the item changed or recursive is set to true
  676. var refreshChildren = child.IsFolder && (currentTuple.Item2 || (recursive.HasValue && recursive.Value));
  677. if (refreshChildren)
  678. {
  679. // Don't refresh children if explicitly set to false
  680. if (recursive.HasValue && recursive.Value == false)
  681. {
  682. refreshChildren = false;
  683. }
  684. }
  685. if (refreshChildren)
  686. {
  687. cancellationToken.ThrowIfCancellationRequested();
  688. var innerProgress = new ActionableProgress<double>();
  689. innerProgress.RegisterAction(p =>
  690. {
  691. lock (percentages)
  692. {
  693. percentages[child.Id] = p / 100;
  694. var percent = percentages.Values.Sum();
  695. percent /= list.Count;
  696. progress.Report((90 * percent) + 10);
  697. }
  698. });
  699. await ((Folder)child).ValidateChildren(innerProgress, cancellationToken, recursive, forceRefreshMetadata).ConfigureAwait(false);
  700. // Some folder providers are unable to refresh until children have been refreshed.
  701. await child.RefreshMetadata(cancellationToken, resetResolveArgs: false).ConfigureAwait(false);
  702. }
  703. else
  704. {
  705. lock (percentages)
  706. {
  707. percentages[child.Id] = 1;
  708. var percent = percentages.Values.Sum();
  709. percent /= list.Count;
  710. progress.Report((90 * percent) + 10);
  711. }
  712. }
  713. }));
  714. }
  715. cancellationToken.ThrowIfCancellationRequested();
  716. await Task.WhenAll(tasks).ConfigureAwait(false);
  717. }
  718. /// <summary>
  719. /// Determines if a path's root is available or not
  720. /// </summary>
  721. /// <param name="path"></param>
  722. /// <returns></returns>
  723. private bool IsRootPathAvailable(string path)
  724. {
  725. if (File.Exists(path))
  726. {
  727. return true;
  728. }
  729. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  730. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  731. {
  732. if (Directory.Exists(path))
  733. {
  734. return true;
  735. }
  736. path = System.IO.Path.GetDirectoryName(path);
  737. }
  738. return false;
  739. }
  740. /// <summary>
  741. /// Get the children of this folder from the actual file system
  742. /// </summary>
  743. /// <returns>IEnumerable{BaseItem}.</returns>
  744. protected virtual IEnumerable<BaseItem> GetNonCachedChildren()
  745. {
  746. if (ResolveArgs == null || ResolveArgs.FileSystemDictionary == null)
  747. {
  748. Logger.Error("Null for {0}", Path);
  749. }
  750. return LibraryManager.ResolvePaths<BaseItem>(ResolveArgs.FileSystemChildren, this);
  751. }
  752. /// <summary>
  753. /// Get our children from the repo - stubbed for now
  754. /// </summary>
  755. /// <returns>IEnumerable{BaseItem}.</returns>
  756. protected IEnumerable<BaseItem> GetCachedChildren()
  757. {
  758. return ItemRepository.GetChildren(Id).Select(RetrieveChild).Where(i => i != null);
  759. }
  760. /// <summary>
  761. /// Retrieves the child.
  762. /// </summary>
  763. /// <param name="child">The child.</param>
  764. /// <returns>BaseItem.</returns>
  765. private BaseItem RetrieveChild(Guid child)
  766. {
  767. var item = LibraryManager.RetrieveItem(child);
  768. if (item != null)
  769. {
  770. if (item is IByReferenceItem)
  771. {
  772. return LibraryManager.GetOrAddByReferenceItem(item);
  773. }
  774. item.Parent = this;
  775. }
  776. return item;
  777. }
  778. /// <summary>
  779. /// Gets allowed children of an item
  780. /// </summary>
  781. /// <param name="user">The user.</param>
  782. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  783. /// <param name="indexBy">The index by.</param>
  784. /// <returns>IEnumerable{BaseItem}.</returns>
  785. /// <exception cref="System.ArgumentNullException"></exception>
  786. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren, string indexBy = null)
  787. {
  788. if (user == null)
  789. {
  790. throw new ArgumentNullException();
  791. }
  792. //the true root should return our users root folder children
  793. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren, indexBy);
  794. IEnumerable<BaseItem> result = null;
  795. if (!string.IsNullOrEmpty(indexBy))
  796. {
  797. result = GetIndexedChildren(user, indexBy);
  798. }
  799. if (result != null)
  800. {
  801. return result;
  802. }
  803. var children = Children;
  804. if (includeLinkedChildren)
  805. {
  806. children = children.Concat(GetLinkedChildren());
  807. }
  808. // If indexed is false or the indexing function is null
  809. return children.Where(c => c.IsVisible(user));
  810. }
  811. /// <summary>
  812. /// Gets allowed recursive children of an item
  813. /// </summary>
  814. /// <param name="user">The user.</param>
  815. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  816. /// <returns>IEnumerable{BaseItem}.</returns>
  817. /// <exception cref="System.ArgumentNullException"></exception>
  818. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  819. {
  820. if (user == null)
  821. {
  822. throw new ArgumentNullException();
  823. }
  824. var children = GetRecursiveChildrenInternal(user, includeLinkedChildren);
  825. if (includeLinkedChildren)
  826. {
  827. children = children.DistinctBy(i => i.Id);
  828. }
  829. return children;
  830. }
  831. /// <summary>
  832. /// Gets allowed recursive children of an item
  833. /// </summary>
  834. /// <param name="user">The user.</param>
  835. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  836. /// <returns>IEnumerable{BaseItem}.</returns>
  837. /// <exception cref="System.ArgumentNullException"></exception>
  838. private IEnumerable<BaseItem> GetRecursiveChildrenInternal(User user, bool includeLinkedChildren)
  839. {
  840. if (user == null)
  841. {
  842. throw new ArgumentNullException();
  843. }
  844. foreach (var item in GetChildren(user, includeLinkedChildren))
  845. {
  846. yield return item;
  847. var subFolder = item as Folder;
  848. if (subFolder != null)
  849. {
  850. foreach (var subitem in subFolder.GetRecursiveChildrenInternal(user, includeLinkedChildren))
  851. {
  852. yield return subitem;
  853. }
  854. }
  855. }
  856. }
  857. /// <summary>
  858. /// Gets the linked children.
  859. /// </summary>
  860. /// <returns>IEnumerable{BaseItem}.</returns>
  861. public IEnumerable<BaseItem> GetLinkedChildren()
  862. {
  863. return LinkedChildren
  864. .Select(GetLinkedChild)
  865. .Where(i => i != null);
  866. }
  867. /// <summary>
  868. /// Gets the linked child.
  869. /// </summary>
  870. /// <param name="info">The info.</param>
  871. /// <returns>BaseItem.</returns>
  872. private BaseItem GetLinkedChild(LinkedChild info)
  873. {
  874. if (string.IsNullOrEmpty(info.Path))
  875. {
  876. throw new ArgumentException("Encountered linked child with empty path.");
  877. }
  878. var item = LibraryManager.RootFolder.FindByPath(info.Path);
  879. if (item == null)
  880. {
  881. Logger.Warn("Unable to find linked item at {0}", info.Path);
  882. }
  883. return item;
  884. }
  885. public override async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  886. {
  887. var changed = await base.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs).ConfigureAwait(false);
  888. return changed || (SupportsShortcutChildren && LocationType == LocationType.FileSystem && RefreshLinkedChildren());
  889. }
  890. /// <summary>
  891. /// Refreshes the linked children.
  892. /// </summary>
  893. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  894. private bool RefreshLinkedChildren()
  895. {
  896. ItemResolveArgs resolveArgs;
  897. try
  898. {
  899. resolveArgs = ResolveArgs;
  900. if (!resolveArgs.IsDirectory)
  901. {
  902. return false;
  903. }
  904. }
  905. catch (IOException ex)
  906. {
  907. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  908. return false;
  909. }
  910. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  911. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  912. var newShortcutLinks = resolveArgs.FileSystemChildren
  913. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  914. .Select(i =>
  915. {
  916. try
  917. {
  918. Logger.Debug("Found shortcut at {0}", i.FullName);
  919. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  920. if (!string.IsNullOrEmpty(resolvedPath))
  921. {
  922. return new LinkedChild
  923. {
  924. Path = resolvedPath,
  925. Type = LinkedChildType.Shortcut
  926. };
  927. }
  928. Logger.Error("Error resolving shortcut {0}", i.FullName);
  929. return null;
  930. }
  931. catch (IOException ex)
  932. {
  933. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  934. return null;
  935. }
  936. })
  937. .Where(i => i != null)
  938. .ToList();
  939. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks))
  940. {
  941. Logger.Info("Shortcut links have changed for {0}", Path);
  942. newShortcutLinks.AddRange(currentManualLinks);
  943. LinkedChildren = newShortcutLinks;
  944. return true;
  945. }
  946. return false;
  947. }
  948. /// <summary>
  949. /// Folders need to validate and refresh
  950. /// </summary>
  951. /// <returns>Task.</returns>
  952. public override async Task ChangedExternally()
  953. {
  954. await base.ChangedExternally().ConfigureAwait(false);
  955. var progress = new Progress<double>();
  956. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  957. }
  958. /// <summary>
  959. /// Marks the item as either played or unplayed
  960. /// </summary>
  961. /// <param name="user">The user.</param>
  962. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  963. /// <param name="userManager">The user manager.</param>
  964. /// <returns>Task.</returns>
  965. public override async Task SetPlayedStatus(User user, bool wasPlayed, IUserDataRepository userManager)
  966. {
  967. // Sweep through recursively and update status
  968. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder).Select(c => c.SetPlayedStatus(user, wasPlayed, userManager));
  969. await Task.WhenAll(tasks).ConfigureAwait(false);
  970. }
  971. /// <summary>
  972. /// Finds an item by path, recursively
  973. /// </summary>
  974. /// <param name="path">The path.</param>
  975. /// <returns>BaseItem.</returns>
  976. /// <exception cref="System.ArgumentNullException"></exception>
  977. public BaseItem FindByPath(string path)
  978. {
  979. if (string.IsNullOrEmpty(path))
  980. {
  981. throw new ArgumentNullException();
  982. }
  983. try
  984. {
  985. if (ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  986. {
  987. return this;
  988. }
  989. }
  990. catch (IOException ex)
  991. {
  992. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  993. }
  994. //this should be functionally equivilent to what was here since it is IEnum and works on a thread-safe copy
  995. return RecursiveChildren.FirstOrDefault(i =>
  996. {
  997. try
  998. {
  999. return i.ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase);
  1000. }
  1001. catch (IOException ex)
  1002. {
  1003. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  1004. return false;
  1005. }
  1006. });
  1007. }
  1008. }
  1009. }