Folder.cs 44 KB

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