Folder.cs 39 KB

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