Folder.cs 50 KB

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