Folder.cs 40 KB

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