Folder.cs 39 KB

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