Folder.cs 40 KB

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