Folder.cs 39 KB

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