Folder.cs 40 KB

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