Folder.cs 45 KB

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