Folder.cs 40 KB

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