Folder.cs 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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. var ids = children.Select(i => i.Id).ToList();
  123. lock (_childrenSyncLock)
  124. {
  125. _children = ActualChildren.Where(i => !ids.Contains(i.Id)).ToList();
  126. }
  127. }
  128. protected void ClearChildrenInternal()
  129. {
  130. lock (_childrenSyncLock)
  131. {
  132. _children = new List<BaseItem>();
  133. }
  134. }
  135. /// <summary>
  136. /// Never want folders to be blocked by "BlockNotRated"
  137. /// </summary>
  138. [IgnoreDataMember]
  139. public override string OfficialRatingForComparison
  140. {
  141. get
  142. {
  143. if (this is Series)
  144. {
  145. return base.OfficialRatingForComparison;
  146. }
  147. return !string.IsNullOrEmpty(base.OfficialRatingForComparison) ? base.OfficialRatingForComparison : "None";
  148. }
  149. }
  150. /// <summary>
  151. /// Removes the child.
  152. /// </summary>
  153. /// <param name="item">The item.</param>
  154. /// <param name="cancellationToken">The cancellation token.</param>
  155. /// <returns>Task.</returns>
  156. /// <exception cref="System.InvalidOperationException">Unable to remove + item.Name</exception>
  157. public Task RemoveChild(BaseItem item, CancellationToken cancellationToken)
  158. {
  159. RemoveChildrenInternal(new[] { item });
  160. item.Parent = null;
  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("StudioDispPref")}
  193. };
  194. }
  195. /// <summary>
  196. /// Get the list of indexy by choices for this folder (localized).
  197. /// </summary>
  198. /// <value>The index by option strings.</value>
  199. [IgnoreDataMember]
  200. public IEnumerable<string> IndexByOptionStrings
  201. {
  202. get { return GetIndexByOptions(); }
  203. }
  204. #endregion
  205. /// <summary>
  206. /// The children
  207. /// </summary>
  208. private IReadOnlyList<BaseItem> _children;
  209. /// <summary>
  210. /// The _children sync lock
  211. /// </summary>
  212. private readonly object _childrenSyncLock = new object();
  213. /// <summary>
  214. /// Gets or sets the actual children.
  215. /// </summary>
  216. /// <value>The actual children.</value>
  217. protected virtual IEnumerable<BaseItem> ActualChildren
  218. {
  219. get
  220. {
  221. return _children ?? (_children = LoadChildrenInternal());
  222. }
  223. }
  224. /// <summary>
  225. /// thread-safe access to the actual children of this folder - without regard to user
  226. /// </summary>
  227. /// <value>The children.</value>
  228. [IgnoreDataMember]
  229. public IEnumerable<BaseItem> Children
  230. {
  231. get { return ActualChildren; }
  232. }
  233. /// <summary>
  234. /// thread-safe access to all recursive children of this folder - without regard to user
  235. /// </summary>
  236. /// <value>The recursive children.</value>
  237. [IgnoreDataMember]
  238. public IEnumerable<BaseItem> RecursiveChildren
  239. {
  240. get { return GetRecursiveChildren(); }
  241. }
  242. public override bool IsVisible(User user)
  243. {
  244. if (this is ICollectionFolder)
  245. {
  246. if (user.Configuration.BlockedMediaFolders.Contains(Name, StringComparer.OrdinalIgnoreCase))
  247. {
  248. return false;
  249. }
  250. }
  251. return base.IsVisible(user);
  252. }
  253. private List<BaseItem> LoadChildrenInternal()
  254. {
  255. return LoadChildren().ToList();
  256. }
  257. /// <summary>
  258. /// Loads our children. Validation will occur externally.
  259. /// We want this sychronous.
  260. /// </summary>
  261. protected virtual IEnumerable<BaseItem> LoadChildren()
  262. {
  263. //just load our children from the repo - the library will be validated and maintained in other processes
  264. return GetCachedChildren();
  265. }
  266. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken)
  267. {
  268. return ValidateChildren(progress, cancellationToken, new MetadataRefreshOptions());
  269. }
  270. /// <summary>
  271. /// Validates that the children of the folder still exist
  272. /// </summary>
  273. /// <param name="progress">The progress.</param>
  274. /// <param name="cancellationToken">The cancellation token.</param>
  275. /// <param name="metadataRefreshOptions">The metadata refresh options.</param>
  276. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  277. /// <returns>Task.</returns>
  278. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken, MetadataRefreshOptions metadataRefreshOptions, bool recursive = true)
  279. {
  280. metadataRefreshOptions.DirectoryService = metadataRefreshOptions.DirectoryService ?? new DirectoryService(Logger);
  281. return ValidateChildrenWithCancellationSupport(progress, cancellationToken, recursive, true, metadataRefreshOptions, metadataRefreshOptions.DirectoryService);
  282. }
  283. private Task ValidateChildrenWithCancellationSupport(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  284. {
  285. return ValidateChildrenInternal(progress, cancellationToken, recursive, refreshChildMetadata, refreshOptions, directoryService);
  286. }
  287. private Dictionary<Guid, BaseItem> GetActualChildrenDictionary()
  288. {
  289. var dictionary = new Dictionary<Guid, BaseItem>();
  290. foreach (var child in ActualChildren)
  291. {
  292. var id = child.Id;
  293. if (dictionary.ContainsKey(id))
  294. {
  295. Logger.Error("Found folder containing items with duplicate id. Path: {0}, Child Name: {1}",
  296. Path ?? Name,
  297. child.Path ?? child.Name);
  298. }
  299. else
  300. {
  301. dictionary[id] = child;
  302. }
  303. }
  304. return dictionary;
  305. }
  306. /// <summary>
  307. /// Validates the children internal.
  308. /// </summary>
  309. /// <param name="progress">The progress.</param>
  310. /// <param name="cancellationToken">The cancellation token.</param>
  311. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  312. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  313. /// <param name="refreshOptions">The refresh options.</param>
  314. /// <param name="directoryService">The directory service.</param>
  315. /// <returns>Task.</returns>
  316. protected async virtual Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  317. {
  318. var locationType = LocationType;
  319. cancellationToken.ThrowIfCancellationRequested();
  320. var validChildren = new List<BaseItem>();
  321. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  322. {
  323. IEnumerable<BaseItem> nonCachedChildren;
  324. try
  325. {
  326. nonCachedChildren = GetNonCachedChildren(directoryService);
  327. }
  328. catch (IOException ex)
  329. {
  330. nonCachedChildren = new BaseItem[] { };
  331. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  332. }
  333. if (nonCachedChildren == null) return; //nothing to validate
  334. progress.Report(5);
  335. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  336. var currentChildren = GetActualChildrenDictionary();
  337. //create a list for our validated children
  338. var newItems = new List<BaseItem>();
  339. cancellationToken.ThrowIfCancellationRequested();
  340. foreach (var child in nonCachedChildren)
  341. {
  342. BaseItem currentChild;
  343. if (currentChildren.TryGetValue(child.Id, out currentChild) && child.IsInMixedFolder == currentChild.IsInMixedFolder)
  344. {
  345. var currentChildLocationType = currentChild.LocationType;
  346. if (currentChildLocationType != LocationType.Remote &&
  347. currentChildLocationType != LocationType.Virtual)
  348. {
  349. currentChild.DateModified = child.DateModified;
  350. }
  351. currentChild.IsOffline = false;
  352. }
  353. else
  354. {
  355. //brand new item - needs to be added
  356. newItems.Add(child);
  357. }
  358. validChildren.Add(currentChild);
  359. }
  360. // If any items were added or removed....
  361. if (newItems.Count > 0 || currentChildren.Count != validChildren.Count)
  362. {
  363. // That's all the new and changed ones - now see if there are any that are missing
  364. var itemsRemoved = currentChildren.Values.Except(validChildren).ToList();
  365. var actualRemovals = new List<BaseItem>();
  366. foreach (var item in itemsRemoved)
  367. {
  368. if (item.LocationType == LocationType.Virtual ||
  369. item.LocationType == LocationType.Remote)
  370. {
  371. // Don't remove these because there's no way to accurately validate them.
  372. validChildren.Add(item);
  373. }
  374. else if (!string.IsNullOrEmpty(item.Path) && IsPathOffline(item.Path))
  375. {
  376. item.IsOffline = true;
  377. validChildren.Add(item);
  378. }
  379. else
  380. {
  381. item.IsOffline = false;
  382. actualRemovals.Add(item);
  383. }
  384. }
  385. if (actualRemovals.Count > 0)
  386. {
  387. RemoveChildrenInternal(actualRemovals);
  388. foreach (var item in actualRemovals)
  389. {
  390. LibraryManager.ReportItemRemoved(item);
  391. }
  392. }
  393. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  394. AddChildrenInternal(newItems);
  395. await ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  396. }
  397. }
  398. progress.Report(10);
  399. cancellationToken.ThrowIfCancellationRequested();
  400. if (recursive)
  401. {
  402. await ValidateSubFolders(ActualChildren.OfType<Folder>().ToList(), directoryService, progress, cancellationToken).ConfigureAwait(false);
  403. }
  404. progress.Report(20);
  405. if (refreshChildMetadata)
  406. {
  407. var container = this as IMetadataContainer;
  408. var innerProgress = new ActionableProgress<double>();
  409. innerProgress.RegisterAction(p => progress.Report((.80 * p) + 20));
  410. if (container != null)
  411. {
  412. await container.RefreshAllMetadata(refreshOptions, innerProgress, cancellationToken).ConfigureAwait(false);
  413. }
  414. else
  415. {
  416. await RefreshMetadataRecursive(refreshOptions, recursive, innerProgress, cancellationToken);
  417. }
  418. }
  419. progress.Report(100);
  420. }
  421. private async Task RefreshMetadataRecursive(MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  422. {
  423. var children = ActualChildren.ToList();
  424. var percentages = new Dictionary<Guid, double>(children.Count);
  425. var tasks = new List<Task>();
  426. foreach (var child in children)
  427. {
  428. if (tasks.Count >= 3)
  429. {
  430. await Task.WhenAll(tasks).ConfigureAwait(false);
  431. tasks.Clear();
  432. }
  433. cancellationToken.ThrowIfCancellationRequested();
  434. var innerProgress = new ActionableProgress<double>();
  435. // Avoid implicitly captured closure
  436. var currentChild = child;
  437. innerProgress.RegisterAction(p =>
  438. {
  439. lock (percentages)
  440. {
  441. percentages[currentChild.Id] = p / 100;
  442. var percent = percentages.Values.Sum();
  443. percent /= children.Count;
  444. percent *= 100;
  445. progress.Report(percent);
  446. }
  447. });
  448. if (child.IsFolder)
  449. {
  450. await RefreshChildMetadata(child, refreshOptions, recursive, innerProgress, cancellationToken)
  451. .ConfigureAwait(false);
  452. }
  453. else
  454. {
  455. // Avoid implicitly captured closure
  456. var taskChild = child;
  457. tasks.Add(Task.Run(async () => await RefreshChildMetadata(taskChild, refreshOptions, false, innerProgress, cancellationToken).ConfigureAwait(false), cancellationToken));
  458. }
  459. }
  460. await Task.WhenAll(tasks).ConfigureAwait(false);
  461. progress.Report(100);
  462. }
  463. private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  464. {
  465. var container = child as IMetadataContainer;
  466. if (container != null)
  467. {
  468. await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  469. }
  470. else
  471. {
  472. await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  473. if (recursive)
  474. {
  475. var folder = child as Folder;
  476. if (folder != null)
  477. {
  478. await folder.RefreshMetadataRecursive(refreshOptions, true, progress, cancellationToken);
  479. }
  480. }
  481. }
  482. progress.Report(100);
  483. }
  484. /// <summary>
  485. /// Refreshes the children.
  486. /// </summary>
  487. /// <param name="children">The children.</param>
  488. /// <param name="directoryService">The directory service.</param>
  489. /// <param name="progress">The progress.</param>
  490. /// <param name="cancellationToken">The cancellation token.</param>
  491. /// <returns>Task.</returns>
  492. private async Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
  493. {
  494. var list = children;
  495. var childCount = list.Count;
  496. var percentages = new Dictionary<Guid, double>(list.Count);
  497. foreach (var item in list)
  498. {
  499. cancellationToken.ThrowIfCancellationRequested();
  500. var child = item;
  501. var innerProgress = new ActionableProgress<double>();
  502. innerProgress.RegisterAction(p =>
  503. {
  504. lock (percentages)
  505. {
  506. percentages[child.Id] = p / 100;
  507. var percent = percentages.Values.Sum();
  508. percent /= childCount;
  509. progress.Report((10 * percent) + 10);
  510. }
  511. });
  512. await child.ValidateChildrenWithCancellationSupport(innerProgress, cancellationToken, true, false, null, directoryService)
  513. .ConfigureAwait(false);
  514. }
  515. }
  516. /// <summary>
  517. /// Determines whether the specified path is offline.
  518. /// </summary>
  519. /// <param name="path">The path.</param>
  520. /// <returns><c>true</c> if the specified path is offline; otherwise, <c>false</c>.</returns>
  521. private bool IsPathOffline(string path)
  522. {
  523. if (File.Exists(path))
  524. {
  525. return false;
  526. }
  527. var originalPath = path;
  528. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  529. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  530. {
  531. if (Directory.Exists(path))
  532. {
  533. return false;
  534. }
  535. path = System.IO.Path.GetDirectoryName(path);
  536. }
  537. if (ContainsPath(LibraryManager.GetDefaultVirtualFolders(), originalPath))
  538. {
  539. return true;
  540. }
  541. return UserManager.Users.Any(user => ContainsPath(LibraryManager.GetVirtualFolders(user), originalPath));
  542. }
  543. /// <summary>
  544. /// Determines whether the specified folders contains path.
  545. /// </summary>
  546. /// <param name="folders">The folders.</param>
  547. /// <param name="path">The path.</param>
  548. /// <returns><c>true</c> if the specified folders contains path; otherwise, <c>false</c>.</returns>
  549. private bool ContainsPath(IEnumerable<VirtualFolderInfo> folders, string path)
  550. {
  551. return folders.SelectMany(i => i.Locations).Any(i => ContainsPath(i, path));
  552. }
  553. private bool ContainsPath(string parent, string path)
  554. {
  555. return string.Equals(parent, path, StringComparison.OrdinalIgnoreCase) || FileSystem.ContainsSubPath(parent, path);
  556. }
  557. /// <summary>
  558. /// Get the children of this folder from the actual file system
  559. /// </summary>
  560. /// <returns>IEnumerable{BaseItem}.</returns>
  561. protected virtual IEnumerable<BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
  562. {
  563. return LibraryManager.ResolvePaths<BaseItem>(GetFileSystemChildren(directoryService), directoryService, this);
  564. }
  565. /// <summary>
  566. /// Get our children from the repo - stubbed for now
  567. /// </summary>
  568. /// <returns>IEnumerable{BaseItem}.</returns>
  569. protected IEnumerable<BaseItem> GetCachedChildren()
  570. {
  571. return ItemRepository.GetChildren(Id).Select(RetrieveChild).Where(i => i != null);
  572. }
  573. /// <summary>
  574. /// Retrieves the child.
  575. /// </summary>
  576. /// <param name="child">The child.</param>
  577. /// <returns>BaseItem.</returns>
  578. private BaseItem RetrieveChild(Guid child)
  579. {
  580. var item = LibraryManager.RetrieveItem(child);
  581. if (item != null)
  582. {
  583. if (item is IByReferenceItem)
  584. {
  585. return LibraryManager.GetOrAddByReferenceItem(item);
  586. }
  587. item.Parent = this;
  588. }
  589. return item;
  590. }
  591. /// <summary>
  592. /// Gets allowed children of an item
  593. /// </summary>
  594. /// <param name="user">The user.</param>
  595. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  596. /// <returns>IEnumerable{BaseItem}.</returns>
  597. /// <exception cref="System.ArgumentNullException"></exception>
  598. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  599. {
  600. if (user == null)
  601. {
  602. throw new ArgumentNullException();
  603. }
  604. //the true root should return our users root folder children
  605. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  606. var list = new List<BaseItem>();
  607. AddChildrenToList(user, includeLinkedChildren, list, false, null);
  608. return list;
  609. }
  610. /// <summary>
  611. /// Adds the children to list.
  612. /// </summary>
  613. /// <param name="user">The user.</param>
  614. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  615. /// <param name="list">The list.</param>
  616. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  617. /// <param name="filter">The filter.</param>
  618. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  619. private bool AddChildrenToList(User user, bool includeLinkedChildren, List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  620. {
  621. var hasLinkedChildren = false;
  622. foreach (var child in Children)
  623. {
  624. if (child.IsVisible(user))
  625. {
  626. if (filter == null || filter(child))
  627. {
  628. list.Add(child);
  629. }
  630. if (recursive && child.IsFolder)
  631. {
  632. var folder = (Folder)child;
  633. if (folder.AddChildrenToList(user, includeLinkedChildren, list, true, filter))
  634. {
  635. hasLinkedChildren = true;
  636. }
  637. }
  638. }
  639. }
  640. if (includeLinkedChildren)
  641. {
  642. foreach (var child in GetLinkedChildren())
  643. {
  644. if (filter != null && !filter(child))
  645. {
  646. continue;
  647. }
  648. if (child.IsVisible(user))
  649. {
  650. hasLinkedChildren = true;
  651. list.Add(child);
  652. }
  653. }
  654. }
  655. return hasLinkedChildren;
  656. }
  657. /// <summary>
  658. /// Gets allowed recursive children of an item
  659. /// </summary>
  660. /// <param name="user">The user.</param>
  661. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  662. /// <returns>IEnumerable{BaseItem}.</returns>
  663. /// <exception cref="System.ArgumentNullException"></exception>
  664. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  665. {
  666. return GetRecursiveChildren(user, null, includeLinkedChildren);
  667. }
  668. /// <summary>
  669. /// Gets the recursive children.
  670. /// </summary>
  671. /// <param name="user">The user.</param>
  672. /// <param name="filter">The filter.</param>
  673. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  674. /// <returns>IList{BaseItem}.</returns>
  675. /// <exception cref="System.ArgumentNullException"></exception>
  676. public IList<BaseItem> GetRecursiveChildren(User user, Func<BaseItem, bool> filter, bool includeLinkedChildren = true)
  677. {
  678. if (user == null)
  679. {
  680. throw new ArgumentNullException("user");
  681. }
  682. var list = new List<BaseItem>();
  683. var hasLinkedChildren = AddChildrenToList(user, includeLinkedChildren, list, true, filter);
  684. return hasLinkedChildren ? list.DistinctBy(i => i.Id).ToList() : list;
  685. }
  686. /// <summary>
  687. /// Gets the recursive children.
  688. /// </summary>
  689. /// <returns>IList{BaseItem}.</returns>
  690. public IList<BaseItem> GetRecursiveChildren()
  691. {
  692. return GetRecursiveChildren(i => true);
  693. }
  694. /// <summary>
  695. /// Gets the recursive children.
  696. /// </summary>
  697. /// <param name="filter">The filter.</param>
  698. /// <returns>IEnumerable{BaseItem}.</returns>
  699. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  700. {
  701. var list = new List<BaseItem>();
  702. AddChildrenToList(list, true, filter);
  703. return list;
  704. }
  705. /// <summary>
  706. /// Adds the children to list.
  707. /// </summary>
  708. /// <param name="list">The list.</param>
  709. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  710. /// <param name="filter">The filter.</param>
  711. private void AddChildrenToList(List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  712. {
  713. foreach (var child in Children)
  714. {
  715. if (filter == null || filter(child))
  716. {
  717. list.Add(child);
  718. }
  719. if (recursive && child.IsFolder)
  720. {
  721. var folder = (Folder)child;
  722. folder.AddChildrenToList(list, true, filter);
  723. }
  724. }
  725. }
  726. /// <summary>
  727. /// Gets the linked children.
  728. /// </summary>
  729. /// <returns>IEnumerable{BaseItem}.</returns>
  730. public IEnumerable<BaseItem> GetLinkedChildren()
  731. {
  732. return LinkedChildren
  733. .Select(GetLinkedChild)
  734. .Where(i => i != null);
  735. }
  736. /// <summary>
  737. /// Gets the linked child.
  738. /// </summary>
  739. /// <param name="info">The info.</param>
  740. /// <returns>BaseItem.</returns>
  741. private BaseItem GetLinkedChild(LinkedChild info)
  742. {
  743. if (string.IsNullOrEmpty(info.Path))
  744. {
  745. throw new ArgumentException("Encountered linked child with empty path.");
  746. }
  747. BaseItem item = null;
  748. // First get using the cached Id
  749. if (info.ItemId.HasValue)
  750. {
  751. if (info.ItemId.Value == Guid.Empty)
  752. {
  753. return null;
  754. }
  755. item = LibraryManager.GetItemById(info.ItemId.Value);
  756. }
  757. // If still null, search by path
  758. if (item == null)
  759. {
  760. item = LibraryManager.RootFolder.FindByPath(info.Path);
  761. }
  762. // If still null, log
  763. if (item == null)
  764. {
  765. Logger.Warn("Unable to find linked item at {0}", info.Path);
  766. // Don't keep searching over and over
  767. info.ItemId = Guid.Empty;
  768. }
  769. else
  770. {
  771. // Cache the id for next time
  772. info.ItemId = item.Id;
  773. }
  774. return item;
  775. }
  776. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  777. {
  778. var changesFound = false;
  779. if (SupportsShortcutChildren && LocationType == LocationType.FileSystem)
  780. {
  781. if (RefreshLinkedChildren(fileSystemChildren))
  782. {
  783. changesFound = true;
  784. }
  785. }
  786. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  787. return baseHasChanges || changesFound;
  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. foreach (var child in LinkedChildren)
  832. {
  833. // Reset the cached value
  834. if (child.ItemId.HasValue && child.ItemId.Value == Guid.Empty)
  835. {
  836. child.ItemId = null;
  837. }
  838. }
  839. return false;
  840. }
  841. /// <summary>
  842. /// Folders need to validate and refresh
  843. /// </summary>
  844. /// <returns>Task.</returns>
  845. public override async Task ChangedExternally()
  846. {
  847. var progress = new Progress<double>();
  848. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  849. await base.ChangedExternally().ConfigureAwait(false);
  850. }
  851. /// <summary>
  852. /// Marks the played.
  853. /// </summary>
  854. /// <param name="user">The user.</param>
  855. /// <param name="datePlayed">The date played.</param>
  856. /// <param name="userManager">The user manager.</param>
  857. /// <returns>Task.</returns>
  858. public override async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataManager userManager)
  859. {
  860. // Sweep through recursively and update status
  861. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual).Select(c => c.MarkPlayed(user, datePlayed, userManager));
  862. await Task.WhenAll(tasks).ConfigureAwait(false);
  863. }
  864. /// <summary>
  865. /// Marks the unplayed.
  866. /// </summary>
  867. /// <param name="user">The user.</param>
  868. /// <param name="userManager">The user manager.</param>
  869. /// <returns>Task.</returns>
  870. public override async Task MarkUnplayed(User user, IUserDataManager userManager)
  871. {
  872. // Sweep through recursively and update status
  873. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual).Select(c => c.MarkUnplayed(user, userManager));
  874. await Task.WhenAll(tasks).ConfigureAwait(false);
  875. }
  876. /// <summary>
  877. /// Finds an item by path, recursively
  878. /// </summary>
  879. /// <param name="path">The path.</param>
  880. /// <returns>BaseItem.</returns>
  881. /// <exception cref="System.ArgumentNullException"></exception>
  882. public BaseItem FindByPath(string path)
  883. {
  884. if (string.IsNullOrEmpty(path))
  885. {
  886. throw new ArgumentNullException();
  887. }
  888. if (string.Equals(Path, path, StringComparison.OrdinalIgnoreCase))
  889. {
  890. return this;
  891. }
  892. if (PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  893. {
  894. return this;
  895. }
  896. return RecursiveChildren.FirstOrDefault(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) ||
  897. (!i.IsFolder && !i.IsInMixedFolder && string.Equals(i.ContainingFolderPath, path, StringComparison.OrdinalIgnoreCase)) ||
  898. i.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase));
  899. }
  900. public override bool IsPlayed(User user)
  901. {
  902. return GetRecursiveChildren(user).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  903. .All(i => i.IsPlayed(user));
  904. }
  905. public override bool IsUnplayed(User user)
  906. {
  907. return GetRecursiveChildren(user).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  908. .All(i => i.IsUnplayed(user));
  909. }
  910. }
  911. }