Folder.cs 38 KB

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