Folder.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  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. var directoryService = new DirectoryService(Logger);
  272. return ValidateChildrenWithCancellationSupport(progress, cancellationToken, recursive ?? true, true,
  273. new MetadataRefreshOptions
  274. {
  275. ReplaceAllMetadata = forceRefreshMetadata,
  276. DirectoryService = directoryService
  277. }, directoryService);
  278. }
  279. private async Task ValidateChildrenWithCancellationSupport(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, DirectoryService directoryService)
  280. {
  281. cancellationToken.ThrowIfCancellationRequested();
  282. // Cancel the current validation, if any
  283. if (CurrentValidationCancellationTokenSource != null)
  284. {
  285. CurrentValidationCancellationTokenSource.Cancel();
  286. }
  287. // Create an inner cancellation token. This can cancel all validations from this level on down,
  288. // but nothing above this
  289. var innerCancellationTokenSource = new CancellationTokenSource();
  290. try
  291. {
  292. CurrentValidationCancellationTokenSource = innerCancellationTokenSource;
  293. var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(innerCancellationTokenSource.Token, cancellationToken);
  294. await ValidateChildrenInternal(progress, linkedCancellationTokenSource.Token, recursive, refreshChildMetadata, refreshOptions, directoryService).ConfigureAwait(false);
  295. }
  296. catch (OperationCanceledException ex)
  297. {
  298. Logger.Info("ValidateChildren cancelled for " + Name);
  299. // If the outer cancelletion token in the cause for the cancellation, throw it
  300. if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken)
  301. {
  302. throw;
  303. }
  304. }
  305. finally
  306. {
  307. // Null out the token source
  308. if (CurrentValidationCancellationTokenSource == innerCancellationTokenSource)
  309. {
  310. CurrentValidationCancellationTokenSource = null;
  311. }
  312. innerCancellationTokenSource.Dispose();
  313. }
  314. }
  315. /// <summary>
  316. /// Validates the children internal.
  317. /// </summary>
  318. /// <param name="progress">The progress.</param>
  319. /// <param name="cancellationToken">The cancellation token.</param>
  320. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  321. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  322. /// <param name="refreshOptions">The refresh options.</param>
  323. /// <param name="directoryService">The directory service.</param>
  324. /// <returns>Task.</returns>
  325. protected async virtual Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, DirectoryService directoryService)
  326. {
  327. var locationType = LocationType;
  328. cancellationToken.ThrowIfCancellationRequested();
  329. var validChildren = new List<BaseItem>();
  330. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  331. {
  332. IEnumerable<BaseItem> nonCachedChildren;
  333. try
  334. {
  335. nonCachedChildren = GetNonCachedChildren(directoryService);
  336. }
  337. catch (IOException ex)
  338. {
  339. nonCachedChildren = new BaseItem[] { };
  340. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  341. }
  342. if (nonCachedChildren == null) return; //nothing to validate
  343. progress.Report(5);
  344. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  345. var currentChildren = ActualChildren.ToDictionary(i => i.Id);
  346. //create a list for our validated children
  347. var newItems = new List<BaseItem>();
  348. cancellationToken.ThrowIfCancellationRequested();
  349. foreach (var child in nonCachedChildren)
  350. {
  351. BaseItem currentChild;
  352. if (currentChildren.TryGetValue(child.Id, out currentChild))
  353. {
  354. var currentChildLocationType = currentChild.LocationType;
  355. if (currentChildLocationType != LocationType.Remote &&
  356. currentChildLocationType != LocationType.Virtual)
  357. {
  358. currentChild.DateModified = child.DateModified;
  359. }
  360. currentChild.IsInMixedFolder = child.IsInMixedFolder;
  361. currentChild.IsOffline = false;
  362. }
  363. else
  364. {
  365. //brand new item - needs to be added
  366. newItems.Add(child);
  367. }
  368. validChildren.Add(currentChild);
  369. }
  370. // If any items were added or removed....
  371. if (newItems.Count > 0 || currentChildren.Count != validChildren.Count)
  372. {
  373. // That's all the new and changed ones - now see if there are any that are missing
  374. var itemsRemoved = currentChildren.Values.Except(validChildren).ToList();
  375. var actualRemovals = new List<BaseItem>();
  376. foreach (var item in itemsRemoved)
  377. {
  378. if (item.LocationType == LocationType.Virtual ||
  379. item.LocationType == LocationType.Remote)
  380. {
  381. // Don't remove these because there's no way to accurately validate them.
  382. validChildren.Add(item);
  383. }
  384. else if (!string.IsNullOrEmpty(item.Path) && IsPathOffline(item.Path))
  385. {
  386. item.IsOffline = true;
  387. validChildren.Add(item);
  388. }
  389. else
  390. {
  391. item.IsOffline = false;
  392. actualRemovals.Add(item);
  393. }
  394. }
  395. if (actualRemovals.Count > 0)
  396. {
  397. RemoveChildrenInternal(actualRemovals);
  398. foreach (var item in actualRemovals)
  399. {
  400. LibraryManager.ReportItemRemoved(item);
  401. }
  402. }
  403. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  404. AddChildrenInternal(newItems);
  405. await ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  406. }
  407. }
  408. progress.Report(10);
  409. cancellationToken.ThrowIfCancellationRequested();
  410. if (recursive)
  411. {
  412. await ValidateSubFolders(ActualChildren.OfType<Folder>().ToList(), directoryService, progress, cancellationToken).ConfigureAwait(false);
  413. }
  414. progress.Report(20);
  415. if (refreshChildMetadata)
  416. {
  417. var container = this as IMetadataContainer;
  418. var innerProgress = new ActionableProgress<double>();
  419. innerProgress.RegisterAction(p => progress.Report((.80 * p) + 20));
  420. if (container != null)
  421. {
  422. await container.RefreshAllMetadata(refreshOptions, innerProgress, cancellationToken).ConfigureAwait(false);
  423. }
  424. else
  425. {
  426. await RefreshMetadataRecursive(refreshOptions, recursive, innerProgress, cancellationToken);
  427. }
  428. }
  429. progress.Report(100);
  430. }
  431. private async Task RefreshMetadataRecursive(MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  432. {
  433. var children = ActualChildren.ToList();
  434. var percentages = new Dictionary<Guid, double>(children.Count);
  435. var tasks = new List<Task>();
  436. foreach (var child in children)
  437. {
  438. if (tasks.Count >= 2)
  439. {
  440. await Task.WhenAll(tasks).ConfigureAwait(false);
  441. tasks.Clear();
  442. }
  443. cancellationToken.ThrowIfCancellationRequested();
  444. var innerProgress = new ActionableProgress<double>();
  445. // Avoid implicitly captured closure
  446. var currentChild = child;
  447. innerProgress.RegisterAction(p =>
  448. {
  449. lock (percentages)
  450. {
  451. percentages[currentChild.Id] = p / 100;
  452. var percent = percentages.Values.Sum();
  453. percent /= children.Count;
  454. percent *= 100;
  455. progress.Report(percent);
  456. }
  457. });
  458. if (child.IsFolder)
  459. {
  460. await RefreshChildMetadata(child, refreshOptions, recursive, innerProgress, cancellationToken)
  461. .ConfigureAwait(false);
  462. }
  463. else
  464. {
  465. tasks.Add(RefreshChildMetadata(child, refreshOptions, false, innerProgress, cancellationToken));
  466. }
  467. }
  468. await Task.WhenAll(tasks).ConfigureAwait(false);
  469. progress.Report(100);
  470. }
  471. private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  472. {
  473. var container = child as IMetadataContainer;
  474. if (container != null)
  475. {
  476. await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  477. }
  478. else
  479. {
  480. await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  481. if (recursive)
  482. {
  483. var folder = child as Folder;
  484. if (folder != null)
  485. {
  486. await folder.RefreshMetadataRecursive(refreshOptions, true, progress, cancellationToken);
  487. }
  488. }
  489. }
  490. progress.Report(100);
  491. }
  492. /// <summary>
  493. /// Refreshes the children.
  494. /// </summary>
  495. /// <param name="children">The children.</param>
  496. /// <param name="directoryService">The directory service.</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, DirectoryService directoryService, 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. foreach (var item in list)
  506. {
  507. cancellationToken.ThrowIfCancellationRequested();
  508. var child = item;
  509. var innerProgress = new ActionableProgress<double>();
  510. innerProgress.RegisterAction(p =>
  511. {
  512. lock (percentages)
  513. {
  514. percentages[child.Id] = p / 100;
  515. var percent = percentages.Values.Sum();
  516. percent /= childCount;
  517. progress.Report((10 * percent) + 10);
  518. }
  519. });
  520. await child.ValidateChildrenWithCancellationSupport(innerProgress, cancellationToken, true, false, null, directoryService)
  521. .ConfigureAwait(false);
  522. }
  523. }
  524. /// <summary>
  525. /// Determines whether the specified path is offline.
  526. /// </summary>
  527. /// <param name="path">The path.</param>
  528. /// <returns><c>true</c> if the specified path is offline; otherwise, <c>false</c>.</returns>
  529. private bool IsPathOffline(string path)
  530. {
  531. if (File.Exists(path))
  532. {
  533. return false;
  534. }
  535. var originalPath = path;
  536. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  537. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  538. {
  539. if (Directory.Exists(path))
  540. {
  541. return false;
  542. }
  543. path = System.IO.Path.GetDirectoryName(path);
  544. }
  545. if (ContainsPath(LibraryManager.GetDefaultVirtualFolders(), originalPath))
  546. {
  547. return true;
  548. }
  549. return UserManager.Users.Any(user => ContainsPath(LibraryManager.GetVirtualFolders(user), originalPath));
  550. }
  551. /// <summary>
  552. /// Determines whether the specified folders contains path.
  553. /// </summary>
  554. /// <param name="folders">The folders.</param>
  555. /// <param name="path">The path.</param>
  556. /// <returns><c>true</c> if the specified folders contains path; otherwise, <c>false</c>.</returns>
  557. private bool ContainsPath(IEnumerable<VirtualFolderInfo> folders, string path)
  558. {
  559. return folders.SelectMany(i => i.Locations).Any(i => ContainsPath(i, path));
  560. }
  561. private bool ContainsPath(string parent, string path)
  562. {
  563. return string.Equals(parent, path, StringComparison.OrdinalIgnoreCase) || FileSystem.ContainsSubPath(parent, path);
  564. }
  565. /// <summary>
  566. /// Get the children of this folder from the actual file system
  567. /// </summary>
  568. /// <returns>IEnumerable{BaseItem}.</returns>
  569. protected virtual IEnumerable<BaseItem> GetNonCachedChildren(DirectoryService directoryService)
  570. {
  571. return LibraryManager.ResolvePaths<BaseItem>(GetFileSystemChildren(directoryService), this);
  572. }
  573. /// <summary>
  574. /// Get our children from the repo - stubbed for now
  575. /// </summary>
  576. /// <returns>IEnumerable{BaseItem}.</returns>
  577. protected IEnumerable<BaseItem> GetCachedChildren()
  578. {
  579. return ItemRepository.GetChildren(Id).Select(RetrieveChild).Where(i => i != null);
  580. }
  581. /// <summary>
  582. /// Retrieves the child.
  583. /// </summary>
  584. /// <param name="child">The child.</param>
  585. /// <returns>BaseItem.</returns>
  586. private BaseItem RetrieveChild(Guid child)
  587. {
  588. var item = LibraryManager.RetrieveItem(child);
  589. if (item != null)
  590. {
  591. if (item is IByReferenceItem)
  592. {
  593. return LibraryManager.GetOrAddByReferenceItem(item);
  594. }
  595. item.Parent = this;
  596. }
  597. return item;
  598. }
  599. /// <summary>
  600. /// Gets allowed children of an item
  601. /// </summary>
  602. /// <param name="user">The user.</param>
  603. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  604. /// <returns>IEnumerable{BaseItem}.</returns>
  605. /// <exception cref="System.ArgumentNullException"></exception>
  606. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  607. {
  608. if (user == null)
  609. {
  610. throw new ArgumentNullException();
  611. }
  612. //the true root should return our users root folder children
  613. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  614. var list = new List<BaseItem>();
  615. AddChildrenToList(user, includeLinkedChildren, list, false, null);
  616. return list;
  617. }
  618. /// <summary>
  619. /// Adds the children to list.
  620. /// </summary>
  621. /// <param name="user">The user.</param>
  622. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  623. /// <param name="list">The list.</param>
  624. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  625. /// <param name="filter">The filter.</param>
  626. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  627. private bool AddChildrenToList(User user, bool includeLinkedChildren, List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  628. {
  629. var hasLinkedChildren = false;
  630. foreach (var child in Children)
  631. {
  632. if (child.IsVisible(user))
  633. {
  634. if (filter == null || filter(child))
  635. {
  636. list.Add(child);
  637. }
  638. }
  639. if (recursive && child.IsFolder)
  640. {
  641. var folder = (Folder)child;
  642. if (folder.AddChildrenToList(user, includeLinkedChildren, list, true, filter))
  643. {
  644. hasLinkedChildren = true;
  645. }
  646. }
  647. }
  648. if (includeLinkedChildren)
  649. {
  650. foreach (var child in GetLinkedChildren())
  651. {
  652. if (filter != null && !filter(child))
  653. {
  654. continue;
  655. }
  656. if (child.IsVisible(user))
  657. {
  658. hasLinkedChildren = true;
  659. list.Add(child);
  660. }
  661. }
  662. }
  663. return hasLinkedChildren;
  664. }
  665. /// <summary>
  666. /// Gets allowed recursive children of an item
  667. /// </summary>
  668. /// <param name="user">The user.</param>
  669. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  670. /// <returns>IEnumerable{BaseItem}.</returns>
  671. /// <exception cref="System.ArgumentNullException"></exception>
  672. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  673. {
  674. return GetRecursiveChildren(user, null, includeLinkedChildren);
  675. }
  676. /// <summary>
  677. /// Gets the recursive children.
  678. /// </summary>
  679. /// <param name="user">The user.</param>
  680. /// <param name="filter">The filter.</param>
  681. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  682. /// <returns>IList{BaseItem}.</returns>
  683. /// <exception cref="System.ArgumentNullException"></exception>
  684. public IList<BaseItem> GetRecursiveChildren(User user, Func<BaseItem, bool> filter, bool includeLinkedChildren = true)
  685. {
  686. if (user == null)
  687. {
  688. throw new ArgumentNullException("user");
  689. }
  690. var list = new List<BaseItem>();
  691. var hasLinkedChildren = AddChildrenToList(user, includeLinkedChildren, list, true, filter);
  692. return hasLinkedChildren ? list.DistinctBy(i => i.Id).ToList() : list;
  693. }
  694. /// <summary>
  695. /// Gets the recursive children.
  696. /// </summary>
  697. /// <returns>IList{BaseItem}.</returns>
  698. public IList<BaseItem> GetRecursiveChildren()
  699. {
  700. return GetRecursiveChildren(i => true);
  701. }
  702. /// <summary>
  703. /// Gets the recursive children.
  704. /// </summary>
  705. /// <param name="filter">The filter.</param>
  706. /// <returns>IEnumerable{BaseItem}.</returns>
  707. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  708. {
  709. var list = new List<BaseItem>();
  710. AddChildrenToList(list, true, filter);
  711. return list;
  712. }
  713. /// <summary>
  714. /// Adds the children to list.
  715. /// </summary>
  716. /// <param name="list">The list.</param>
  717. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  718. /// <param name="filter">The filter.</param>
  719. private void AddChildrenToList(List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  720. {
  721. foreach (var child in Children)
  722. {
  723. if (filter == null || filter(child))
  724. {
  725. list.Add(child);
  726. }
  727. if (recursive && child.IsFolder)
  728. {
  729. var folder = (Folder)child;
  730. folder.AddChildrenToList(list, true, filter);
  731. }
  732. }
  733. }
  734. /// <summary>
  735. /// Gets the linked children.
  736. /// </summary>
  737. /// <returns>IEnumerable{BaseItem}.</returns>
  738. public IEnumerable<BaseItem> GetLinkedChildren()
  739. {
  740. return LinkedChildren
  741. .Select(GetLinkedChild)
  742. .Where(i => i != null);
  743. }
  744. /// <summary>
  745. /// Gets the linked child.
  746. /// </summary>
  747. /// <param name="info">The info.</param>
  748. /// <returns>BaseItem.</returns>
  749. private BaseItem GetLinkedChild(LinkedChild info)
  750. {
  751. if (string.IsNullOrEmpty(info.Path))
  752. {
  753. throw new ArgumentException("Encountered linked child with empty path.");
  754. }
  755. BaseItem item = null;
  756. // First get using the cached Id
  757. if (info.ItemId != Guid.Empty)
  758. {
  759. item = LibraryManager.GetItemById(info.ItemId) as BaseItem;
  760. }
  761. // If still null, search by path
  762. if (item == null)
  763. {
  764. item = LibraryManager.RootFolder.FindByPath(info.Path);
  765. }
  766. // If still null, log
  767. if (item == null)
  768. {
  769. Logger.Warn("Unable to find linked item at {0}", info.Path);
  770. }
  771. else
  772. {
  773. // Cache the id for next time
  774. info.ItemId = item.Id;
  775. }
  776. return item;
  777. }
  778. protected override Task BeforeRefreshMetadata(MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  779. {
  780. if (SupportsShortcutChildren && LocationType == LocationType.FileSystem)
  781. {
  782. if (RefreshLinkedChildren(fileSystemChildren))
  783. {
  784. options.ForceSave = true;
  785. }
  786. }
  787. return base.BeforeRefreshMetadata(options, fileSystemChildren, cancellationToken);
  788. }
  789. /// <summary>
  790. /// Refreshes the linked children.
  791. /// </summary>
  792. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  793. private bool RefreshLinkedChildren(IEnumerable<FileSystemInfo> fileSystemChildren)
  794. {
  795. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  796. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  797. var newShortcutLinks = fileSystemChildren
  798. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  799. .Select(i =>
  800. {
  801. try
  802. {
  803. Logger.Debug("Found shortcut at {0}", i.FullName);
  804. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  805. if (!string.IsNullOrEmpty(resolvedPath))
  806. {
  807. return new LinkedChild
  808. {
  809. Path = resolvedPath,
  810. Type = LinkedChildType.Shortcut
  811. };
  812. }
  813. Logger.Error("Error resolving shortcut {0}", i.FullName);
  814. return null;
  815. }
  816. catch (IOException ex)
  817. {
  818. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  819. return null;
  820. }
  821. })
  822. .Where(i => i != null)
  823. .ToList();
  824. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  825. {
  826. Logger.Info("Shortcut links have changed for {0}", Path);
  827. newShortcutLinks.AddRange(currentManualLinks);
  828. LinkedChildren = newShortcutLinks;
  829. return true;
  830. }
  831. return false;
  832. }
  833. /// <summary>
  834. /// Folders need to validate and refresh
  835. /// </summary>
  836. /// <returns>Task.</returns>
  837. public override async Task ChangedExternally()
  838. {
  839. var progress = new Progress<double>();
  840. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  841. await base.ChangedExternally().ConfigureAwait(false);
  842. }
  843. /// <summary>
  844. /// Marks the played.
  845. /// </summary>
  846. /// <param name="user">The user.</param>
  847. /// <param name="datePlayed">The date played.</param>
  848. /// <param name="userManager">The user manager.</param>
  849. /// <returns>Task.</returns>
  850. public override async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataManager userManager)
  851. {
  852. // Sweep through recursively and update status
  853. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual).Select(c => c.MarkPlayed(user, datePlayed, userManager));
  854. await Task.WhenAll(tasks).ConfigureAwait(false);
  855. }
  856. /// <summary>
  857. /// Marks the unplayed.
  858. /// </summary>
  859. /// <param name="user">The user.</param>
  860. /// <param name="userManager">The user manager.</param>
  861. /// <returns>Task.</returns>
  862. public override async Task MarkUnplayed(User user, IUserDataManager userManager)
  863. {
  864. // Sweep through recursively and update status
  865. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual).Select(c => c.MarkUnplayed(user, userManager));
  866. await Task.WhenAll(tasks).ConfigureAwait(false);
  867. }
  868. /// <summary>
  869. /// Finds an item by path, recursively
  870. /// </summary>
  871. /// <param name="path">The path.</param>
  872. /// <returns>BaseItem.</returns>
  873. /// <exception cref="System.ArgumentNullException"></exception>
  874. public BaseItem FindByPath(string path)
  875. {
  876. if (string.IsNullOrEmpty(path))
  877. {
  878. throw new ArgumentNullException();
  879. }
  880. try
  881. {
  882. var locationType = LocationType;
  883. if (locationType == LocationType.Remote && string.Equals(Path, path, StringComparison.OrdinalIgnoreCase))
  884. {
  885. return this;
  886. }
  887. if (locationType != LocationType.Virtual && PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  888. {
  889. return this;
  890. }
  891. }
  892. catch (IOException ex)
  893. {
  894. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  895. }
  896. return RecursiveChildren.Where(i => i.LocationType != LocationType.Virtual).FirstOrDefault(i =>
  897. {
  898. try
  899. {
  900. if (string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase))
  901. {
  902. return true;
  903. }
  904. if (i.LocationType != LocationType.Remote)
  905. {
  906. if (i.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  907. {
  908. return true;
  909. }
  910. }
  911. return false;
  912. }
  913. catch (IOException ex)
  914. {
  915. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  916. return false;
  917. }
  918. });
  919. }
  920. public override bool IsPlayed(User user)
  921. {
  922. return GetRecursiveChildren(user).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  923. .All(i => i.IsPlayed(user));
  924. }
  925. public override bool IsUnplayed(User user)
  926. {
  927. return GetRecursiveChildren(user).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  928. .All(i => i.IsUnplayed(user));
  929. }
  930. }
  931. }