Folder.cs 41 KB

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