Folder.cs 39 KB

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