Folder.cs 40 KB

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