Folder.cs 41 KB

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