Folder.cs 39 KB

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