Folder.cs 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538
  1. using MediaBrowser.Common.Progress;
  2. using MediaBrowser.Controller.Library;
  3. using MediaBrowser.Controller.Providers;
  4. using MediaBrowser.Model.Dto;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.Querying;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using MediaBrowser.Controller.Channels;
  14. using MediaBrowser.Controller.Dto;
  15. using MediaBrowser.Controller.Entities.Audio;
  16. using MediaBrowser.Controller.Entities.Movies;
  17. using MediaBrowser.Controller.Entities.TV;
  18. using MediaBrowser.Controller.IO;
  19. using MediaBrowser.Model.Channels;
  20. using MediaBrowser.Model.IO;
  21. using MediaBrowser.Model.Serialization;
  22. using MediaBrowser.Model.Extensions;
  23. namespace MediaBrowser.Controller.Entities
  24. {
  25. /// <summary>
  26. /// Class Folder
  27. /// </summary>
  28. public class Folder : BaseItem
  29. {
  30. public static IUserManager UserManager { get; set; }
  31. public static IUserViewManager UserViewManager { get; set; }
  32. /// <summary>
  33. /// Gets or sets a value indicating whether this instance is root.
  34. /// </summary>
  35. /// <value><c>true</c> if this instance is root; otherwise, <c>false</c>.</value>
  36. public bool IsRoot { get; set; }
  37. public LinkedChild[] LinkedChildren { get; set; }
  38. [IgnoreDataMember]
  39. public DateTime? DateLastMediaAdded { get; set; }
  40. public Folder()
  41. {
  42. LinkedChildren = EmptyLinkedChildArray;
  43. }
  44. [IgnoreDataMember]
  45. public override bool SupportsThemeMedia
  46. {
  47. get { return true; }
  48. }
  49. [IgnoreDataMember]
  50. public virtual bool IsPreSorted
  51. {
  52. get { return false; }
  53. }
  54. [IgnoreDataMember]
  55. public virtual bool IsPhysicalRoot
  56. {
  57. get { return false; }
  58. }
  59. [IgnoreDataMember]
  60. public override bool SupportsInheritedParentImages
  61. {
  62. get
  63. {
  64. return true;
  65. }
  66. }
  67. [IgnoreDataMember]
  68. public override bool SupportsPlayedStatus
  69. {
  70. get
  71. {
  72. return true;
  73. }
  74. }
  75. /// <summary>
  76. /// Gets a value indicating whether this instance is folder.
  77. /// </summary>
  78. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  79. [IgnoreDataMember]
  80. public override bool IsFolder
  81. {
  82. get
  83. {
  84. return true;
  85. }
  86. }
  87. [IgnoreDataMember]
  88. public override bool IsDisplayedAsFolder
  89. {
  90. get
  91. {
  92. return true;
  93. }
  94. }
  95. [IgnoreDataMember]
  96. public virtual bool SupportsCumulativeRunTimeTicks
  97. {
  98. get
  99. {
  100. return false;
  101. }
  102. }
  103. [IgnoreDataMember]
  104. public virtual bool SupportsDateLastMediaAdded
  105. {
  106. get
  107. {
  108. return false;
  109. }
  110. }
  111. public override bool CanDelete()
  112. {
  113. if (IsRoot)
  114. {
  115. return false;
  116. }
  117. return base.CanDelete();
  118. }
  119. public override bool RequiresRefresh()
  120. {
  121. var baseResult = base.RequiresRefresh();
  122. if (SupportsCumulativeRunTimeTicks && !RunTimeTicks.HasValue)
  123. {
  124. baseResult = true;
  125. }
  126. return baseResult;
  127. }
  128. [IgnoreDataMember]
  129. public override string FileNameWithoutExtension
  130. {
  131. get
  132. {
  133. if (LocationType == LocationType.FileSystem)
  134. {
  135. return System.IO.Path.GetFileName(Path);
  136. }
  137. return null;
  138. }
  139. }
  140. protected override bool IsAllowTagFilterEnforced()
  141. {
  142. if (this is ICollectionFolder)
  143. {
  144. return false;
  145. }
  146. if (this is UserView)
  147. {
  148. return false;
  149. }
  150. return true;
  151. }
  152. [IgnoreDataMember]
  153. protected virtual bool SupportsShortcutChildren
  154. {
  155. get { return false; }
  156. }
  157. /// <summary>
  158. /// Adds the child.
  159. /// </summary>
  160. /// <param name="item">The item.</param>
  161. /// <param name="cancellationToken">The cancellation token.</param>
  162. /// <returns>Task.</returns>
  163. /// <exception cref="System.InvalidOperationException">Unable to add + item.Name</exception>
  164. public async Task AddChild(BaseItem item, CancellationToken cancellationToken)
  165. {
  166. item.SetParent(this);
  167. if (item.Id == Guid.Empty)
  168. {
  169. item.Id = LibraryManager.GetNewItemId(item.Path, item.GetType());
  170. }
  171. if (Children.Any(i => i.Id == item.Id))
  172. {
  173. throw new ArgumentException(string.Format("A child with the Id {0} already exists.", item.Id));
  174. }
  175. if (item.DateCreated == DateTime.MinValue)
  176. {
  177. item.DateCreated = DateTime.UtcNow;
  178. }
  179. if (item.DateModified == DateTime.MinValue)
  180. {
  181. item.DateModified = DateTime.UtcNow;
  182. }
  183. await LibraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  184. }
  185. /// <summary>
  186. /// Removes the child.
  187. /// </summary>
  188. /// <param name="item">The item.</param>
  189. public void RemoveChild(BaseItem item)
  190. {
  191. item.SetParent(null);
  192. }
  193. /// <summary>
  194. /// Gets the actual children.
  195. /// </summary>
  196. /// <value>The actual children.</value>
  197. [IgnoreDataMember]
  198. public virtual IEnumerable<BaseItem> Children
  199. {
  200. get
  201. {
  202. return LoadChildren();
  203. }
  204. }
  205. /// <summary>
  206. /// thread-safe access to all recursive children of this folder - without regard to user
  207. /// </summary>
  208. /// <value>The recursive children.</value>
  209. [IgnoreDataMember]
  210. public IEnumerable<BaseItem> RecursiveChildren
  211. {
  212. get { return GetRecursiveChildren(); }
  213. }
  214. public override bool IsVisible(User user)
  215. {
  216. if (this is ICollectionFolder && !(this is BasePluginFolder))
  217. {
  218. if (user.Policy.BlockedMediaFolders != null)
  219. {
  220. if (user.Policy.BlockedMediaFolders.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase) ||
  221. // Backwards compatibility
  222. user.Policy.BlockedMediaFolders.Contains(Name, StringComparer.OrdinalIgnoreCase))
  223. {
  224. return false;
  225. }
  226. }
  227. else
  228. {
  229. if (!user.Policy.EnableAllFolders && !user.Policy.EnabledFolders.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase))
  230. {
  231. return false;
  232. }
  233. }
  234. }
  235. return base.IsVisible(user);
  236. }
  237. /// <summary>
  238. /// Loads our children. Validation will occur externally.
  239. /// We want this sychronous.
  240. /// </summary>
  241. protected virtual List<BaseItem> LoadChildren()
  242. {
  243. //Logger.Debug("Loading children from {0} {1} {2}", GetType().Name, Id, Path);
  244. //just load our children from the repo - the library will be validated and maintained in other processes
  245. return GetCachedChildren();
  246. }
  247. public override double? GetRefreshProgress()
  248. {
  249. return ProviderManager.GetRefreshProgress(Id);
  250. }
  251. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken)
  252. {
  253. return ValidateChildren(progress, cancellationToken, new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem)));
  254. }
  255. /// <summary>
  256. /// Validates that the children of the folder still exist
  257. /// </summary>
  258. /// <param name="progress">The progress.</param>
  259. /// <param name="cancellationToken">The cancellation token.</param>
  260. /// <param name="metadataRefreshOptions">The metadata refresh options.</param>
  261. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  262. /// <returns>Task.</returns>
  263. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken, MetadataRefreshOptions metadataRefreshOptions, bool recursive = true)
  264. {
  265. return ValidateChildrenInternal(progress, cancellationToken, recursive, true, metadataRefreshOptions, metadataRefreshOptions.DirectoryService);
  266. }
  267. private Dictionary<Guid, BaseItem> GetActualChildrenDictionary()
  268. {
  269. var dictionary = new Dictionary<Guid, BaseItem>();
  270. var childrenList = Children.ToList();
  271. foreach (var child in childrenList)
  272. {
  273. var id = child.Id;
  274. if (dictionary.ContainsKey(id))
  275. {
  276. Logger.Error("Found folder containing items with duplicate id. Path: {0}, Child Name: {1}",
  277. Path ?? Name,
  278. child.Path ?? child.Name);
  279. }
  280. else
  281. {
  282. dictionary[id] = child;
  283. }
  284. }
  285. return dictionary;
  286. }
  287. private bool IsValidFromResolver(BaseItem current, BaseItem newItem)
  288. {
  289. return current.IsValidFromResolver(newItem);
  290. }
  291. protected override void TriggerOnRefreshStart()
  292. {
  293. }
  294. protected override void TriggerOnRefreshComplete()
  295. {
  296. }
  297. /// <summary>
  298. /// Validates the children internal.
  299. /// </summary>
  300. /// <param name="progress">The progress.</param>
  301. /// <param name="cancellationToken">The cancellation token.</param>
  302. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  303. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  304. /// <param name="refreshOptions">The refresh options.</param>
  305. /// <param name="directoryService">The directory service.</param>
  306. /// <returns>Task.</returns>
  307. protected virtual async Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  308. {
  309. if (recursive)
  310. {
  311. ProviderManager.OnRefreshStart(this);
  312. }
  313. try
  314. {
  315. await ValidateChildrenInternal2(progress, cancellationToken, recursive, refreshChildMetadata, refreshOptions, directoryService).ConfigureAwait(false);
  316. }
  317. finally
  318. {
  319. if (recursive)
  320. {
  321. ProviderManager.OnRefreshComplete(this);
  322. }
  323. }
  324. }
  325. private async Task ValidateChildrenInternal2(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  326. {
  327. var locationType = LocationType;
  328. cancellationToken.ThrowIfCancellationRequested();
  329. var validChildren = new List<BaseItem>();
  330. var allLibraryPaths = LibraryManager
  331. .GetVirtualFolders()
  332. .SelectMany(i => i.Locations)
  333. .ToList();
  334. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  335. {
  336. IEnumerable<BaseItem> nonCachedChildren;
  337. try
  338. {
  339. nonCachedChildren = GetNonCachedChildren(directoryService);
  340. }
  341. catch (IOException ex)
  342. {
  343. nonCachedChildren = new BaseItem[] { };
  344. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  345. }
  346. if (nonCachedChildren == null) return; //nothing to validate
  347. progress.Report(5);
  348. if (recursive)
  349. {
  350. ProviderManager.OnRefreshProgress(this, 5);
  351. }
  352. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  353. var currentChildren = GetActualChildrenDictionary();
  354. //create a list for our validated children
  355. var newItems = new List<BaseItem>();
  356. cancellationToken.ThrowIfCancellationRequested();
  357. foreach (var child in nonCachedChildren)
  358. {
  359. BaseItem currentChild;
  360. if (currentChildren.TryGetValue(child.Id, out currentChild) && IsValidFromResolver(currentChild, child))
  361. {
  362. validChildren.Add(currentChild);
  363. continue;
  364. }
  365. // Brand new item - needs to be added
  366. child.SetParent(this);
  367. newItems.Add(child);
  368. validChildren.Add(child);
  369. }
  370. // If any items were added or removed....
  371. if (newItems.Count > 0 || currentChildren.Count != validChildren.Count)
  372. {
  373. // That's all the new and changed ones - now see if there are any that are missing
  374. var itemsRemoved = currentChildren.Values.Except(validChildren).ToList();
  375. var actualRemovals = new List<BaseItem>();
  376. foreach (var item in itemsRemoved)
  377. {
  378. var itemLocationType = item.LocationType;
  379. if (itemLocationType == LocationType.Virtual ||
  380. itemLocationType == LocationType.Remote)
  381. {
  382. }
  383. else if (!string.IsNullOrEmpty(item.Path) && IsPathOffline(item.Path, allLibraryPaths))
  384. {
  385. }
  386. else
  387. {
  388. actualRemovals.Add(item);
  389. }
  390. }
  391. if (actualRemovals.Count > 0)
  392. {
  393. foreach (var item in actualRemovals)
  394. {
  395. Logger.Debug("Removed item: " + item.Path);
  396. item.SetParent(null);
  397. await LibraryManager.DeleteItem(item, new DeleteOptions { DeleteFileLocation = false }).ConfigureAwait(false);
  398. LibraryManager.ReportItemRemoved(item);
  399. }
  400. }
  401. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  402. }
  403. }
  404. else
  405. {
  406. if (recursive || refreshChildMetadata)
  407. {
  408. // used below
  409. validChildren = Children.ToList();
  410. }
  411. }
  412. progress.Report(10);
  413. if (recursive)
  414. {
  415. ProviderManager.OnRefreshProgress(this, 10);
  416. }
  417. cancellationToken.ThrowIfCancellationRequested();
  418. if (recursive)
  419. {
  420. using (var innerProgress = new ActionableProgress<double>())
  421. {
  422. var folder = this;
  423. innerProgress.RegisterAction(p =>
  424. {
  425. double newPct = .80 * p + 10;
  426. progress.Report(newPct);
  427. ProviderManager.OnRefreshProgress(folder, newPct);
  428. });
  429. await ValidateSubFolders(validChildren.OfType<Folder>().ToList(), directoryService, innerProgress, cancellationToken).ConfigureAwait(false);
  430. }
  431. }
  432. if (refreshChildMetadata)
  433. {
  434. progress.Report(90);
  435. if (recursive)
  436. {
  437. ProviderManager.OnRefreshProgress(this, 90);
  438. }
  439. var container = this as IMetadataContainer;
  440. using (var innerProgress = new ActionableProgress<double>())
  441. {
  442. var folder = this;
  443. innerProgress.RegisterAction(p =>
  444. {
  445. double newPct = .10 * p + 90;
  446. progress.Report(newPct);
  447. if (recursive)
  448. {
  449. ProviderManager.OnRefreshProgress(folder, newPct);
  450. }
  451. });
  452. if (container != null)
  453. {
  454. await container.RefreshAllMetadata(refreshOptions, innerProgress, cancellationToken).ConfigureAwait(false);
  455. }
  456. else
  457. {
  458. await RefreshMetadataRecursive(validChildren, refreshOptions, recursive, innerProgress, cancellationToken);
  459. }
  460. }
  461. }
  462. }
  463. private async Task RefreshMetadataRecursive(List<BaseItem> children, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  464. {
  465. var numComplete = 0;
  466. var count = children.Count;
  467. double currentPercent = 0;
  468. foreach (var child in children)
  469. {
  470. cancellationToken.ThrowIfCancellationRequested();
  471. using (var innerProgress = new ActionableProgress<double>())
  472. {
  473. // Avoid implicitly captured closure
  474. var currentInnerPercent = currentPercent;
  475. innerProgress.RegisterAction(p =>
  476. {
  477. double innerPercent = currentInnerPercent;
  478. innerPercent += p / (count);
  479. progress.Report(innerPercent);
  480. });
  481. await RefreshChildMetadata(child, refreshOptions, recursive && child.IsFolder, innerProgress, cancellationToken)
  482. .ConfigureAwait(false);
  483. }
  484. numComplete++;
  485. double percent = numComplete;
  486. percent /= count;
  487. percent *= 100;
  488. currentPercent = percent;
  489. progress.Report(percent);
  490. }
  491. }
  492. private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  493. {
  494. var container = child as IMetadataContainer;
  495. if (container != null)
  496. {
  497. await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  498. }
  499. else
  500. {
  501. await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  502. if (recursive)
  503. {
  504. var folder = child as Folder;
  505. if (folder != null)
  506. {
  507. await folder.RefreshMetadataRecursive(folder.Children.ToList(), refreshOptions, true, progress, cancellationToken);
  508. }
  509. }
  510. }
  511. }
  512. /// <summary>
  513. /// Refreshes the children.
  514. /// </summary>
  515. /// <param name="children">The children.</param>
  516. /// <param name="directoryService">The directory service.</param>
  517. /// <param name="progress">The progress.</param>
  518. /// <param name="cancellationToken">The cancellation token.</param>
  519. /// <returns>Task.</returns>
  520. private async Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
  521. {
  522. var numComplete = 0;
  523. var count = children.Count;
  524. double currentPercent = 0;
  525. foreach (var child in children)
  526. {
  527. cancellationToken.ThrowIfCancellationRequested();
  528. using (var innerProgress = new ActionableProgress<double>())
  529. {
  530. // Avoid implicitly captured closure
  531. var currentInnerPercent = currentPercent;
  532. innerProgress.RegisterAction(p =>
  533. {
  534. double innerPercent = currentInnerPercent;
  535. innerPercent += p / (count);
  536. progress.Report(innerPercent);
  537. });
  538. await child.ValidateChildrenInternal(innerProgress, cancellationToken, true, false, null, directoryService)
  539. .ConfigureAwait(false);
  540. }
  541. numComplete++;
  542. double percent = numComplete;
  543. percent /= count;
  544. percent *= 100;
  545. currentPercent = percent;
  546. progress.Report(percent);
  547. }
  548. }
  549. public static bool IsPathOffline(string path, List<string> allLibraryPaths)
  550. {
  551. if (FileSystem.FileExists(path))
  552. {
  553. return false;
  554. }
  555. var originalPath = path;
  556. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  557. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  558. {
  559. if (FileSystem.DirectoryExists(path))
  560. {
  561. return false;
  562. }
  563. if (allLibraryPaths.Contains(path, StringComparer.OrdinalIgnoreCase))
  564. {
  565. return true;
  566. }
  567. path = FileSystem.GetDirectoryName(path);
  568. }
  569. return allLibraryPaths.Any(i => ContainsPath(i, originalPath));
  570. }
  571. private static bool ContainsPath(string parent, string path)
  572. {
  573. return FileSystem.AreEqual(parent, path) || FileSystem.ContainsSubPath(parent, path);
  574. }
  575. /// <summary>
  576. /// Get the children of this folder from the actual file system
  577. /// </summary>
  578. /// <returns>IEnumerable{BaseItem}.</returns>
  579. protected virtual IEnumerable<BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
  580. {
  581. var collectionType = LibraryManager.GetContentType(this);
  582. var libraryOptions = LibraryManager.GetLibraryOptions(this);
  583. return LibraryManager.ResolvePaths(GetFileSystemChildren(directoryService), directoryService, this, libraryOptions, collectionType);
  584. }
  585. /// <summary>
  586. /// Get our children from the repo - stubbed for now
  587. /// </summary>
  588. /// <returns>IEnumerable{BaseItem}.</returns>
  589. protected List<BaseItem> GetCachedChildren()
  590. {
  591. return ItemRepository.GetItemList(new InternalItemsQuery
  592. {
  593. Parent = this,
  594. GroupByPresentationUniqueKey = false,
  595. DtoOptions = new DtoOptions(true)
  596. });
  597. }
  598. public virtual int GetChildCount(User user)
  599. {
  600. if (LinkedChildren.Length > 0)
  601. {
  602. if (!(this is ICollectionFolder))
  603. {
  604. return GetChildren(user, true).Count();
  605. }
  606. }
  607. var result = GetItems(new InternalItemsQuery(user)
  608. {
  609. Recursive = false,
  610. Limit = 0,
  611. Parent = this,
  612. DtoOptions = new DtoOptions(false)
  613. {
  614. EnableImages = false
  615. }
  616. });
  617. return result.TotalRecordCount;
  618. }
  619. public virtual int GetRecursiveChildCount(User user)
  620. {
  621. return GetItems(new InternalItemsQuery(user)
  622. {
  623. Recursive = true,
  624. IsFolder = false,
  625. IsVirtualItem = false,
  626. EnableTotalRecordCount = true,
  627. Limit = 0,
  628. DtoOptions = new DtoOptions(false)
  629. {
  630. EnableImages = false
  631. }
  632. }).TotalRecordCount;
  633. }
  634. public QueryResult<BaseItem> QueryRecursive(InternalItemsQuery query)
  635. {
  636. var user = query.User;
  637. if (!query.ForceDirect && RequiresPostFiltering(query))
  638. {
  639. IEnumerable<BaseItem> items;
  640. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  641. if (query.User == null)
  642. {
  643. items = GetRecursiveChildren(filter);
  644. }
  645. else
  646. {
  647. items = GetRecursiveChildren(user, query);
  648. }
  649. return PostFilterAndSort(items, query, true, true);
  650. }
  651. if (!(this is UserRootFolder) && !(this is AggregateFolder))
  652. {
  653. if (!query.ParentId.HasValue)
  654. {
  655. query.Parent = this;
  656. }
  657. }
  658. if (RequiresPostFiltering2(query))
  659. {
  660. return QueryWithPostFiltering2(query);
  661. }
  662. return LibraryManager.GetItemsResult(query);
  663. }
  664. private QueryResult<BaseItem> QueryWithPostFiltering2(InternalItemsQuery query)
  665. {
  666. var startIndex = query.StartIndex;
  667. var limit = query.Limit;
  668. query.StartIndex = null;
  669. query.Limit = null;
  670. IEnumerable<BaseItem> itemsList = LibraryManager.GetItemList(query);
  671. var user = query.User;
  672. if (user != null)
  673. {
  674. // needed for boxsets
  675. itemsList = itemsList.Where(i => i.IsVisibleStandalone(query.User));
  676. }
  677. IEnumerable<BaseItem> returnItems;
  678. int totalCount = 0;
  679. if (query.EnableTotalRecordCount)
  680. {
  681. var itemsArray = itemsList.ToArray();
  682. totalCount = itemsArray.Length;
  683. returnItems = itemsArray;
  684. }
  685. else
  686. {
  687. returnItems = itemsList;
  688. }
  689. if (limit.HasValue)
  690. {
  691. returnItems = returnItems.Skip(startIndex ?? 0).Take(limit.Value);
  692. }
  693. else if (startIndex.HasValue)
  694. {
  695. returnItems = returnItems.Skip(startIndex.Value);
  696. }
  697. return new QueryResult<BaseItem>
  698. {
  699. TotalRecordCount = totalCount,
  700. Items = returnItems.ToArray()
  701. };
  702. }
  703. private bool RequiresPostFiltering2(InternalItemsQuery query)
  704. {
  705. if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], typeof(BoxSet).Name, StringComparison.OrdinalIgnoreCase))
  706. {
  707. Logger.Debug("Query requires post-filtering due to BoxSet query");
  708. return true;
  709. }
  710. return false;
  711. }
  712. private bool RequiresPostFiltering(InternalItemsQuery query)
  713. {
  714. if (LinkedChildren.Length > 0)
  715. {
  716. if (!(this is ICollectionFolder))
  717. {
  718. Logger.Debug("Query requires post-filtering due to LinkedChildren. Type: " + GetType().Name);
  719. return true;
  720. }
  721. }
  722. if (query.IsInBoxSet.HasValue)
  723. {
  724. Logger.Debug("Query requires post-filtering due to IsInBoxSet");
  725. return true;
  726. }
  727. // Filter by Video3DFormat
  728. if (query.Is3D.HasValue)
  729. {
  730. Logger.Debug("Query requires post-filtering due to Is3D");
  731. return true;
  732. }
  733. if (query.HasOfficialRating.HasValue)
  734. {
  735. Logger.Debug("Query requires post-filtering due to HasOfficialRating");
  736. return true;
  737. }
  738. if (query.IsPlaceHolder.HasValue)
  739. {
  740. Logger.Debug("Query requires post-filtering due to IsPlaceHolder");
  741. return true;
  742. }
  743. if (query.HasSpecialFeature.HasValue)
  744. {
  745. Logger.Debug("Query requires post-filtering due to HasSpecialFeature");
  746. return true;
  747. }
  748. if (query.HasSubtitles.HasValue)
  749. {
  750. Logger.Debug("Query requires post-filtering due to HasSubtitles");
  751. return true;
  752. }
  753. if (query.HasTrailer.HasValue)
  754. {
  755. Logger.Debug("Query requires post-filtering due to HasTrailer");
  756. return true;
  757. }
  758. // Filter by VideoType
  759. if (query.VideoTypes.Length > 0)
  760. {
  761. Logger.Debug("Query requires post-filtering due to VideoTypes");
  762. return true;
  763. }
  764. // Apply person filter
  765. if (query.ItemIdsFromPersonFilters != null)
  766. {
  767. Logger.Debug("Query requires post-filtering due to ItemIdsFromPersonFilters");
  768. return true;
  769. }
  770. if (UserViewBuilder.CollapseBoxSetItems(query, this, query.User, ConfigurationManager))
  771. {
  772. Logger.Debug("Query requires post-filtering due to CollapseBoxSetItems");
  773. return true;
  774. }
  775. if (!string.IsNullOrWhiteSpace(query.AdjacentTo))
  776. {
  777. Logger.Debug("Query requires post-filtering due to AdjacentTo");
  778. return true;
  779. }
  780. if (query.AirDays.Length > 0)
  781. {
  782. Logger.Debug("Query requires post-filtering due to AirDays");
  783. return true;
  784. }
  785. if (query.SeriesStatuses.Length > 0)
  786. {
  787. Logger.Debug("Query requires post-filtering due to SeriesStatuses");
  788. return true;
  789. }
  790. if (query.AiredDuringSeason.HasValue)
  791. {
  792. Logger.Debug("Query requires post-filtering due to AiredDuringSeason");
  793. return true;
  794. }
  795. if (query.IsPlayed.HasValue)
  796. {
  797. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(typeof(Series).Name))
  798. {
  799. Logger.Debug("Query requires post-filtering due to IsPlayed");
  800. return true;
  801. }
  802. }
  803. return false;
  804. }
  805. public QueryResult<BaseItem> GetItems(InternalItemsQuery query)
  806. {
  807. if (query.ItemIds.Length > 0)
  808. {
  809. var result = LibraryManager.GetItemsResult(query);
  810. if (query.SortBy.Length == 0)
  811. {
  812. var ids = query.ItemIds.ToList();
  813. // Try to preserve order
  814. result.Items = result.Items.OrderBy(i => ids.IndexOf(i.Id.ToString("N"))).ToArray();
  815. }
  816. return result;
  817. }
  818. return GetItemsInternal(query);
  819. }
  820. public BaseItem[] GetItemList(InternalItemsQuery query)
  821. {
  822. query.EnableTotalRecordCount = false;
  823. if (query.ItemIds.Length > 0)
  824. {
  825. var result = LibraryManager.GetItemList(query);
  826. if (query.SortBy.Length == 0)
  827. {
  828. var ids = query.ItemIds.ToList();
  829. // Try to preserve order
  830. return result.OrderBy(i => ids.IndexOf(i.Id.ToString("N"))).ToArray();
  831. }
  832. return result.ToArray(result.Count);
  833. }
  834. return GetItemsInternal(query).Items;
  835. }
  836. protected virtual QueryResult<BaseItem> GetItemsInternal(InternalItemsQuery query)
  837. {
  838. if (SourceType == SourceType.Channel)
  839. {
  840. try
  841. {
  842. // Don't blow up here because it could cause parent screens with other content to fail
  843. return ChannelManager.GetChannelItemsInternal(new ChannelItemQuery
  844. {
  845. ChannelId = ChannelId,
  846. FolderId = Id.ToString("N"),
  847. Limit = query.Limit,
  848. StartIndex = query.StartIndex,
  849. UserId = query.User.Id.ToString("N"),
  850. SortBy = query.SortBy,
  851. SortOrder = query.SortOrder
  852. }, new SimpleProgress<double>(), CancellationToken.None).Result;
  853. }
  854. catch
  855. {
  856. // Already logged at lower levels
  857. return new QueryResult<BaseItem>();
  858. }
  859. }
  860. if (query.Recursive)
  861. {
  862. return QueryRecursive(query);
  863. }
  864. var user = query.User;
  865. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  866. IEnumerable<BaseItem> items;
  867. if (query.User == null)
  868. {
  869. items = query.Recursive
  870. ? GetRecursiveChildren(filter)
  871. : Children.Where(filter);
  872. }
  873. else
  874. {
  875. items = query.Recursive
  876. ? GetRecursiveChildren(user, query)
  877. : GetChildren(user, true).Where(filter);
  878. }
  879. return PostFilterAndSort(items, query, true, true);
  880. }
  881. protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query, bool collapseBoxSetItems, bool enableSorting)
  882. {
  883. return UserViewBuilder.PostFilterAndSort(items, this, null, query, LibraryManager, ConfigurationManager, collapseBoxSetItems, enableSorting);
  884. }
  885. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  886. {
  887. if (user == null)
  888. {
  889. throw new ArgumentNullException();
  890. }
  891. //the true root should return our users root folder children
  892. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  893. var result = new Dictionary<Guid, BaseItem>();
  894. AddChildren(user, includeLinkedChildren, result, false, null);
  895. return result.Values;
  896. }
  897. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  898. {
  899. return Children;
  900. }
  901. /// <summary>
  902. /// Adds the children to list.
  903. /// </summary>
  904. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  905. private void AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, InternalItemsQuery query)
  906. {
  907. foreach (var child in GetEligibleChildrenForRecursiveChildren(user))
  908. {
  909. if (child.IsVisible(user))
  910. {
  911. if (query == null || UserViewBuilder.FilterItem(child, query))
  912. {
  913. result[child.Id] = child;
  914. }
  915. if (recursive && child.IsFolder)
  916. {
  917. var folder = (Folder)child;
  918. folder.AddChildren(user, includeLinkedChildren, result, true, query);
  919. }
  920. }
  921. }
  922. if (includeLinkedChildren)
  923. {
  924. foreach (var child in GetLinkedChildren(user))
  925. {
  926. if (child.IsVisible(user))
  927. {
  928. if (query == null || UserViewBuilder.FilterItem(child, query))
  929. {
  930. result[child.Id] = child;
  931. }
  932. }
  933. }
  934. }
  935. }
  936. /// <summary>
  937. /// Gets allowed recursive children of an item
  938. /// </summary>
  939. /// <param name="user">The user.</param>
  940. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  941. /// <returns>IEnumerable{BaseItem}.</returns>
  942. /// <exception cref="System.ArgumentNullException"></exception>
  943. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  944. {
  945. return GetRecursiveChildren(user, null);
  946. }
  947. public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query)
  948. {
  949. if (user == null)
  950. {
  951. throw new ArgumentNullException("user");
  952. }
  953. var result = new Dictionary<Guid, BaseItem>();
  954. AddChildren(user, true, result, true, query);
  955. return result.Values;
  956. }
  957. /// <summary>
  958. /// Gets the recursive children.
  959. /// </summary>
  960. /// <returns>IList{BaseItem}.</returns>
  961. public IList<BaseItem> GetRecursiveChildren()
  962. {
  963. return GetRecursiveChildren(true);
  964. }
  965. public IList<BaseItem> GetRecursiveChildren(bool includeLinkedChildren)
  966. {
  967. return GetRecursiveChildren(i => true, includeLinkedChildren);
  968. }
  969. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  970. {
  971. return GetRecursiveChildren(filter, true);
  972. }
  973. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter, bool includeLinkedChildren)
  974. {
  975. var result = new Dictionary<Guid, BaseItem>();
  976. AddChildrenToList(result, includeLinkedChildren, true, filter);
  977. return result.Values.ToList();
  978. }
  979. /// <summary>
  980. /// Adds the children to list.
  981. /// </summary>
  982. private void AddChildrenToList(Dictionary<Guid, BaseItem> result, bool includeLinkedChildren, bool recursive, Func<BaseItem, bool> filter)
  983. {
  984. foreach (var child in Children)
  985. {
  986. if (filter == null || filter(child))
  987. {
  988. result[child.Id] = child;
  989. }
  990. if (recursive && child.IsFolder)
  991. {
  992. var folder = (Folder)child;
  993. // We can only support includeLinkedChildren for the first folder, or we might end up stuck in a loop of linked items
  994. folder.AddChildrenToList(result, false, true, filter);
  995. }
  996. }
  997. if (includeLinkedChildren)
  998. {
  999. foreach (var child in GetLinkedChildren())
  1000. {
  1001. if (filter == null || filter(child))
  1002. {
  1003. result[child.Id] = child;
  1004. }
  1005. }
  1006. }
  1007. }
  1008. /// <summary>
  1009. /// Gets the linked children.
  1010. /// </summary>
  1011. /// <returns>IEnumerable{BaseItem}.</returns>
  1012. public IEnumerable<BaseItem> GetLinkedChildren()
  1013. {
  1014. return LinkedChildren
  1015. .Select(GetLinkedChild)
  1016. .Where(i => i != null);
  1017. }
  1018. protected virtual bool FilterLinkedChildrenPerUser
  1019. {
  1020. get
  1021. {
  1022. return false;
  1023. }
  1024. }
  1025. public IEnumerable<BaseItem> GetLinkedChildren(User user)
  1026. {
  1027. if (!FilterLinkedChildrenPerUser || user == null)
  1028. {
  1029. return GetLinkedChildren();
  1030. }
  1031. if (LinkedChildren.Length == 0)
  1032. {
  1033. return new List<BaseItem>();
  1034. }
  1035. var allUserRootChildren = user.RootFolder.Children.OfType<Folder>().ToList();
  1036. var collectionFolderIds = allUserRootChildren
  1037. .OfType<CollectionFolder>()
  1038. .Where(i => i.IsVisible(user))
  1039. .Select(i => i.Id)
  1040. .ToList();
  1041. return LinkedChildren
  1042. .Select(i =>
  1043. {
  1044. var child = GetLinkedChild(i);
  1045. if (child != null)
  1046. {
  1047. var childLocationType = child.LocationType;
  1048. if (childLocationType == LocationType.Remote || childLocationType == LocationType.Virtual)
  1049. {
  1050. if (!child.IsVisibleStandalone(user))
  1051. {
  1052. return null;
  1053. }
  1054. }
  1055. else if (childLocationType == LocationType.FileSystem)
  1056. {
  1057. var itemCollectionFolderIds =
  1058. LibraryManager.GetCollectionFolders(child, allUserRootChildren)
  1059. .Select(f => f.Id).ToList();
  1060. if (!itemCollectionFolderIds.Any(collectionFolderIds.Contains))
  1061. {
  1062. return null;
  1063. }
  1064. }
  1065. }
  1066. return child;
  1067. })
  1068. .Where(i => i != null);
  1069. }
  1070. /// <summary>
  1071. /// Gets the linked children.
  1072. /// </summary>
  1073. /// <returns>IEnumerable{BaseItem}.</returns>
  1074. public IEnumerable<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  1075. {
  1076. return LinkedChildren
  1077. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  1078. .Where(i => i.Item2 != null);
  1079. }
  1080. [IgnoreDataMember]
  1081. protected override bool SupportsOwnedItems
  1082. {
  1083. get
  1084. {
  1085. return base.SupportsOwnedItems || SupportsShortcutChildren;
  1086. }
  1087. }
  1088. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1089. {
  1090. var changesFound = false;
  1091. if (LocationType == LocationType.FileSystem)
  1092. {
  1093. if (RefreshLinkedChildren(fileSystemChildren))
  1094. {
  1095. changesFound = true;
  1096. }
  1097. }
  1098. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1099. return baseHasChanges || changesFound;
  1100. }
  1101. /// <summary>
  1102. /// Refreshes the linked children.
  1103. /// </summary>
  1104. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1105. protected virtual bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  1106. {
  1107. if (SupportsShortcutChildren)
  1108. {
  1109. var newShortcutLinks = fileSystemChildren
  1110. .Where(i => !i.IsDirectory && FileSystem.IsShortcut(i.FullName))
  1111. .Select(i =>
  1112. {
  1113. try
  1114. {
  1115. Logger.Debug("Found shortcut at {0}", i.FullName);
  1116. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  1117. if (!string.IsNullOrEmpty(resolvedPath))
  1118. {
  1119. return new LinkedChild
  1120. {
  1121. Path = resolvedPath,
  1122. Type = LinkedChildType.Shortcut
  1123. };
  1124. }
  1125. Logger.Error("Error resolving shortcut {0}", i.FullName);
  1126. return null;
  1127. }
  1128. catch (IOException ex)
  1129. {
  1130. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  1131. return null;
  1132. }
  1133. })
  1134. .Where(i => i != null)
  1135. .ToList();
  1136. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1137. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer(FileSystem)))
  1138. {
  1139. Logger.Info("Shortcut links have changed for {0}", Path);
  1140. newShortcutLinks.AddRange(LinkedChildren.Where(i => i.Type == LinkedChildType.Manual));
  1141. LinkedChildren = newShortcutLinks.ToArray(newShortcutLinks.Count);
  1142. return true;
  1143. }
  1144. }
  1145. foreach (var child in LinkedChildren)
  1146. {
  1147. // Reset the cached value
  1148. child.ItemId = null;
  1149. }
  1150. return false;
  1151. }
  1152. /// <summary>
  1153. /// Marks the played.
  1154. /// </summary>
  1155. /// <param name="user">The user.</param>
  1156. /// <param name="datePlayed">The date played.</param>
  1157. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1158. /// <returns>Task.</returns>
  1159. public override async Task MarkPlayed(User user,
  1160. DateTime? datePlayed,
  1161. bool resetPosition)
  1162. {
  1163. var query = new InternalItemsQuery
  1164. {
  1165. User = user,
  1166. Recursive = true,
  1167. IsFolder = false,
  1168. EnableTotalRecordCount = false
  1169. };
  1170. if (!user.Configuration.DisplayMissingEpisodes || !user.Configuration.DisplayUnairedEpisodes)
  1171. {
  1172. query.IsVirtualItem = false;
  1173. }
  1174. var itemsResult = GetItemList(query);
  1175. // Sweep through recursively and update status
  1176. var tasks = itemsResult.Select(c => c.MarkPlayed(user, datePlayed, resetPosition));
  1177. await Task.WhenAll(tasks).ConfigureAwait(false);
  1178. }
  1179. /// <summary>
  1180. /// Marks the unplayed.
  1181. /// </summary>
  1182. /// <param name="user">The user.</param>
  1183. /// <returns>Task.</returns>
  1184. public override async Task MarkUnplayed(User user)
  1185. {
  1186. var itemsResult = GetItemList(new InternalItemsQuery
  1187. {
  1188. User = user,
  1189. Recursive = true,
  1190. IsFolder = false,
  1191. EnableTotalRecordCount = false
  1192. });
  1193. // Sweep through recursively and update status
  1194. var tasks = itemsResult.Select(c => c.MarkUnplayed(user));
  1195. await Task.WhenAll(tasks).ConfigureAwait(false);
  1196. }
  1197. public override bool IsPlayed(User user)
  1198. {
  1199. var itemsResult = GetItemList(new InternalItemsQuery(user)
  1200. {
  1201. Recursive = true,
  1202. IsFolder = false,
  1203. IsVirtualItem = false,
  1204. EnableTotalRecordCount = false
  1205. });
  1206. return itemsResult
  1207. .All(i => i.IsPlayed(user));
  1208. }
  1209. public override bool IsUnplayed(User user)
  1210. {
  1211. return !IsPlayed(user);
  1212. }
  1213. [IgnoreDataMember]
  1214. public virtual bool SupportsUserDataFromChildren
  1215. {
  1216. get
  1217. {
  1218. // These are just far too slow.
  1219. if (this is ICollectionFolder)
  1220. {
  1221. return false;
  1222. }
  1223. if (this is UserView)
  1224. {
  1225. return false;
  1226. }
  1227. if (this is UserRootFolder)
  1228. {
  1229. return false;
  1230. }
  1231. if (this is Channel)
  1232. {
  1233. return false;
  1234. }
  1235. if (SourceType != SourceType.Library)
  1236. {
  1237. return false;
  1238. }
  1239. var iItemByName = this as IItemByName;
  1240. if (iItemByName != null)
  1241. {
  1242. var hasDualAccess = this as IHasDualAccess;
  1243. if (hasDualAccess == null || hasDualAccess.IsAccessedByName)
  1244. {
  1245. return false;
  1246. }
  1247. }
  1248. return true;
  1249. }
  1250. }
  1251. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, List<ItemFields> fields)
  1252. {
  1253. if (!SupportsUserDataFromChildren)
  1254. {
  1255. return;
  1256. }
  1257. if (itemDto != null)
  1258. {
  1259. if (fields.Contains(ItemFields.RecursiveItemCount))
  1260. {
  1261. itemDto.RecursiveItemCount = GetRecursiveChildCount(user);
  1262. }
  1263. }
  1264. if (SupportsPlayedStatus)
  1265. {
  1266. var unplayedQueryResult = GetItems(new InternalItemsQuery(user)
  1267. {
  1268. Recursive = true,
  1269. IsFolder = false,
  1270. IsVirtualItem = false,
  1271. EnableTotalRecordCount = true,
  1272. Limit = 0,
  1273. IsPlayed = false,
  1274. DtoOptions = new DtoOptions(false)
  1275. {
  1276. EnableImages = false
  1277. }
  1278. });
  1279. double unplayedCount = unplayedQueryResult.TotalRecordCount;
  1280. dto.UnplayedItemCount = unplayedQueryResult.TotalRecordCount;
  1281. if (itemDto != null && itemDto.RecursiveItemCount.HasValue)
  1282. {
  1283. if (itemDto.RecursiveItemCount.Value > 0)
  1284. {
  1285. var unplayedPercentage = (unplayedCount / itemDto.RecursiveItemCount.Value) * 100;
  1286. dto.PlayedPercentage = 100 - unplayedPercentage;
  1287. dto.Played = dto.PlayedPercentage.Value >= 100;
  1288. }
  1289. }
  1290. else
  1291. {
  1292. dto.Played = (dto.UnplayedItemCount ?? 0) == 0;
  1293. }
  1294. }
  1295. }
  1296. }
  1297. }