Folder.cs 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  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.SeriesStatuses.Length > 0)
  781. {
  782. Logger.Debug("Query requires post-filtering due to SeriesStatuses");
  783. return true;
  784. }
  785. if (query.AiredDuringSeason.HasValue)
  786. {
  787. Logger.Debug("Query requires post-filtering due to AiredDuringSeason");
  788. return true;
  789. }
  790. if (query.IsPlayed.HasValue)
  791. {
  792. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(typeof(Series).Name))
  793. {
  794. Logger.Debug("Query requires post-filtering due to IsPlayed");
  795. return true;
  796. }
  797. }
  798. return false;
  799. }
  800. public QueryResult<BaseItem> GetItems(InternalItemsQuery query)
  801. {
  802. if (query.ItemIds.Length > 0)
  803. {
  804. var result = LibraryManager.GetItemsResult(query);
  805. if (query.SortBy.Length == 0)
  806. {
  807. var ids = query.ItemIds.ToList();
  808. // Try to preserve order
  809. result.Items = result.Items.OrderBy(i => ids.IndexOf(i.Id.ToString("N"))).ToArray();
  810. }
  811. return result;
  812. }
  813. return GetItemsInternal(query);
  814. }
  815. public BaseItem[] GetItemList(InternalItemsQuery query)
  816. {
  817. query.EnableTotalRecordCount = false;
  818. if (query.ItemIds.Length > 0)
  819. {
  820. var result = LibraryManager.GetItemList(query);
  821. if (query.SortBy.Length == 0)
  822. {
  823. var ids = query.ItemIds.ToList();
  824. // Try to preserve order
  825. return result.OrderBy(i => ids.IndexOf(i.Id.ToString("N"))).ToArray();
  826. }
  827. return result.ToArray(result.Count);
  828. }
  829. return GetItemsInternal(query).Items;
  830. }
  831. protected virtual QueryResult<BaseItem> GetItemsInternal(InternalItemsQuery query)
  832. {
  833. if (SourceType == SourceType.Channel)
  834. {
  835. try
  836. {
  837. // Don't blow up here because it could cause parent screens with other content to fail
  838. return ChannelManager.GetChannelItemsInternal(new ChannelItemQuery
  839. {
  840. ChannelId = ChannelId,
  841. FolderId = Id.ToString("N"),
  842. Limit = query.Limit,
  843. StartIndex = query.StartIndex,
  844. UserId = query.User.Id.ToString("N"),
  845. SortBy = query.SortBy,
  846. SortOrder = query.SortOrder
  847. }, new SimpleProgress<double>(), CancellationToken.None).Result;
  848. }
  849. catch
  850. {
  851. // Already logged at lower levels
  852. return new QueryResult<BaseItem>();
  853. }
  854. }
  855. if (query.Recursive)
  856. {
  857. return QueryRecursive(query);
  858. }
  859. var user = query.User;
  860. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  861. IEnumerable<BaseItem> items;
  862. if (query.User == null)
  863. {
  864. items = query.Recursive
  865. ? GetRecursiveChildren(filter)
  866. : Children.Where(filter);
  867. }
  868. else
  869. {
  870. items = query.Recursive
  871. ? GetRecursiveChildren(user, query)
  872. : GetChildren(user, true).Where(filter);
  873. }
  874. return PostFilterAndSort(items, query, true, true);
  875. }
  876. protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query, bool collapseBoxSetItems, bool enableSorting)
  877. {
  878. return UserViewBuilder.PostFilterAndSort(items, this, null, query, LibraryManager, ConfigurationManager, collapseBoxSetItems, enableSorting);
  879. }
  880. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  881. {
  882. if (user == null)
  883. {
  884. throw new ArgumentNullException();
  885. }
  886. //the true root should return our users root folder children
  887. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  888. var result = new Dictionary<Guid, BaseItem>();
  889. AddChildren(user, includeLinkedChildren, result, false, null);
  890. return result.Values;
  891. }
  892. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  893. {
  894. return Children;
  895. }
  896. /// <summary>
  897. /// Adds the children to list.
  898. /// </summary>
  899. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  900. private void AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, InternalItemsQuery query)
  901. {
  902. foreach (var child in GetEligibleChildrenForRecursiveChildren(user))
  903. {
  904. if (child.IsVisible(user))
  905. {
  906. if (query == null || UserViewBuilder.FilterItem(child, query))
  907. {
  908. result[child.Id] = child;
  909. }
  910. if (recursive && child.IsFolder)
  911. {
  912. var folder = (Folder)child;
  913. folder.AddChildren(user, includeLinkedChildren, result, true, query);
  914. }
  915. }
  916. }
  917. if (includeLinkedChildren)
  918. {
  919. foreach (var child in GetLinkedChildren(user))
  920. {
  921. if (child.IsVisible(user))
  922. {
  923. if (query == null || UserViewBuilder.FilterItem(child, query))
  924. {
  925. result[child.Id] = child;
  926. }
  927. }
  928. }
  929. }
  930. }
  931. /// <summary>
  932. /// Gets allowed recursive children of an item
  933. /// </summary>
  934. /// <param name="user">The user.</param>
  935. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  936. /// <returns>IEnumerable{BaseItem}.</returns>
  937. /// <exception cref="System.ArgumentNullException"></exception>
  938. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  939. {
  940. return GetRecursiveChildren(user, null);
  941. }
  942. public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query)
  943. {
  944. if (user == null)
  945. {
  946. throw new ArgumentNullException("user");
  947. }
  948. var result = new Dictionary<Guid, BaseItem>();
  949. AddChildren(user, true, result, true, query);
  950. return result.Values;
  951. }
  952. /// <summary>
  953. /// Gets the recursive children.
  954. /// </summary>
  955. /// <returns>IList{BaseItem}.</returns>
  956. public IList<BaseItem> GetRecursiveChildren()
  957. {
  958. return GetRecursiveChildren(true);
  959. }
  960. public IList<BaseItem> GetRecursiveChildren(bool includeLinkedChildren)
  961. {
  962. return GetRecursiveChildren(i => true, includeLinkedChildren);
  963. }
  964. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  965. {
  966. return GetRecursiveChildren(filter, true);
  967. }
  968. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter, bool includeLinkedChildren)
  969. {
  970. var result = new Dictionary<Guid, BaseItem>();
  971. AddChildrenToList(result, includeLinkedChildren, true, filter);
  972. return result.Values.ToList();
  973. }
  974. /// <summary>
  975. /// Adds the children to list.
  976. /// </summary>
  977. private void AddChildrenToList(Dictionary<Guid, BaseItem> result, bool includeLinkedChildren, bool recursive, Func<BaseItem, bool> filter)
  978. {
  979. foreach (var child in Children)
  980. {
  981. if (filter == null || filter(child))
  982. {
  983. result[child.Id] = child;
  984. }
  985. if (recursive && child.IsFolder)
  986. {
  987. var folder = (Folder)child;
  988. // We can only support includeLinkedChildren for the first folder, or we might end up stuck in a loop of linked items
  989. folder.AddChildrenToList(result, false, true, filter);
  990. }
  991. }
  992. if (includeLinkedChildren)
  993. {
  994. foreach (var child in GetLinkedChildren())
  995. {
  996. if (filter == null || filter(child))
  997. {
  998. result[child.Id] = child;
  999. }
  1000. }
  1001. }
  1002. }
  1003. /// <summary>
  1004. /// Gets the linked children.
  1005. /// </summary>
  1006. /// <returns>IEnumerable{BaseItem}.</returns>
  1007. public IEnumerable<BaseItem> GetLinkedChildren()
  1008. {
  1009. return LinkedChildren
  1010. .Select(GetLinkedChild)
  1011. .Where(i => i != null);
  1012. }
  1013. protected virtual bool FilterLinkedChildrenPerUser
  1014. {
  1015. get
  1016. {
  1017. return false;
  1018. }
  1019. }
  1020. public IEnumerable<BaseItem> GetLinkedChildren(User user)
  1021. {
  1022. if (!FilterLinkedChildrenPerUser || user == null)
  1023. {
  1024. return GetLinkedChildren();
  1025. }
  1026. if (LinkedChildren.Length == 0)
  1027. {
  1028. return new List<BaseItem>();
  1029. }
  1030. var allUserRootChildren = user.RootFolder.Children.OfType<Folder>().ToList();
  1031. var collectionFolderIds = allUserRootChildren
  1032. .OfType<CollectionFolder>()
  1033. .Where(i => i.IsVisible(user))
  1034. .Select(i => i.Id)
  1035. .ToList();
  1036. return LinkedChildren
  1037. .Select(i =>
  1038. {
  1039. var child = GetLinkedChild(i);
  1040. if (child != null)
  1041. {
  1042. var childLocationType = child.LocationType;
  1043. if (childLocationType == LocationType.Remote || childLocationType == LocationType.Virtual)
  1044. {
  1045. if (!child.IsVisibleStandalone(user))
  1046. {
  1047. return null;
  1048. }
  1049. }
  1050. else if (childLocationType == LocationType.FileSystem)
  1051. {
  1052. var itemCollectionFolderIds =
  1053. LibraryManager.GetCollectionFolders(child, allUserRootChildren)
  1054. .Select(f => f.Id).ToList();
  1055. if (!itemCollectionFolderIds.Any(collectionFolderIds.Contains))
  1056. {
  1057. return null;
  1058. }
  1059. }
  1060. }
  1061. return child;
  1062. })
  1063. .Where(i => i != null);
  1064. }
  1065. /// <summary>
  1066. /// Gets the linked children.
  1067. /// </summary>
  1068. /// <returns>IEnumerable{BaseItem}.</returns>
  1069. public IEnumerable<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  1070. {
  1071. return LinkedChildren
  1072. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  1073. .Where(i => i.Item2 != null);
  1074. }
  1075. [IgnoreDataMember]
  1076. protected override bool SupportsOwnedItems
  1077. {
  1078. get
  1079. {
  1080. return base.SupportsOwnedItems || SupportsShortcutChildren;
  1081. }
  1082. }
  1083. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1084. {
  1085. var changesFound = false;
  1086. if (LocationType == LocationType.FileSystem)
  1087. {
  1088. if (RefreshLinkedChildren(fileSystemChildren))
  1089. {
  1090. changesFound = true;
  1091. }
  1092. }
  1093. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1094. return baseHasChanges || changesFound;
  1095. }
  1096. /// <summary>
  1097. /// Refreshes the linked children.
  1098. /// </summary>
  1099. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1100. protected virtual bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  1101. {
  1102. if (SupportsShortcutChildren)
  1103. {
  1104. var newShortcutLinks = fileSystemChildren
  1105. .Where(i => !i.IsDirectory && FileSystem.IsShortcut(i.FullName))
  1106. .Select(i =>
  1107. {
  1108. try
  1109. {
  1110. Logger.Debug("Found shortcut at {0}", i.FullName);
  1111. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  1112. if (!string.IsNullOrEmpty(resolvedPath))
  1113. {
  1114. return new LinkedChild
  1115. {
  1116. Path = resolvedPath,
  1117. Type = LinkedChildType.Shortcut
  1118. };
  1119. }
  1120. Logger.Error("Error resolving shortcut {0}", i.FullName);
  1121. return null;
  1122. }
  1123. catch (IOException ex)
  1124. {
  1125. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  1126. return null;
  1127. }
  1128. })
  1129. .Where(i => i != null)
  1130. .ToList();
  1131. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1132. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer(FileSystem)))
  1133. {
  1134. Logger.Info("Shortcut links have changed for {0}", Path);
  1135. newShortcutLinks.AddRange(LinkedChildren.Where(i => i.Type == LinkedChildType.Manual));
  1136. LinkedChildren = newShortcutLinks.ToArray(newShortcutLinks.Count);
  1137. return true;
  1138. }
  1139. }
  1140. foreach (var child in LinkedChildren)
  1141. {
  1142. // Reset the cached value
  1143. child.ItemId = null;
  1144. }
  1145. return false;
  1146. }
  1147. /// <summary>
  1148. /// Marks the played.
  1149. /// </summary>
  1150. /// <param name="user">The user.</param>
  1151. /// <param name="datePlayed">The date played.</param>
  1152. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1153. /// <returns>Task.</returns>
  1154. public override async Task MarkPlayed(User user,
  1155. DateTime? datePlayed,
  1156. bool resetPosition)
  1157. {
  1158. var query = new InternalItemsQuery
  1159. {
  1160. User = user,
  1161. Recursive = true,
  1162. IsFolder = false,
  1163. EnableTotalRecordCount = false
  1164. };
  1165. if (!user.Configuration.DisplayMissingEpisodes)
  1166. {
  1167. query.IsVirtualItem = false;
  1168. }
  1169. var itemsResult = GetItemList(query);
  1170. // Sweep through recursively and update status
  1171. var tasks = itemsResult.Select(c => c.MarkPlayed(user, datePlayed, resetPosition));
  1172. await Task.WhenAll(tasks).ConfigureAwait(false);
  1173. }
  1174. /// <summary>
  1175. /// Marks the unplayed.
  1176. /// </summary>
  1177. /// <param name="user">The user.</param>
  1178. /// <returns>Task.</returns>
  1179. public override async Task MarkUnplayed(User user)
  1180. {
  1181. var itemsResult = GetItemList(new InternalItemsQuery
  1182. {
  1183. User = user,
  1184. Recursive = true,
  1185. IsFolder = false,
  1186. EnableTotalRecordCount = false
  1187. });
  1188. // Sweep through recursively and update status
  1189. var tasks = itemsResult.Select(c => c.MarkUnplayed(user));
  1190. await Task.WhenAll(tasks).ConfigureAwait(false);
  1191. }
  1192. public override bool IsPlayed(User user)
  1193. {
  1194. var itemsResult = GetItemList(new InternalItemsQuery(user)
  1195. {
  1196. Recursive = true,
  1197. IsFolder = false,
  1198. IsVirtualItem = false,
  1199. EnableTotalRecordCount = false
  1200. });
  1201. return itemsResult
  1202. .All(i => i.IsPlayed(user));
  1203. }
  1204. public override bool IsUnplayed(User user)
  1205. {
  1206. return !IsPlayed(user);
  1207. }
  1208. [IgnoreDataMember]
  1209. public virtual bool SupportsUserDataFromChildren
  1210. {
  1211. get
  1212. {
  1213. // These are just far too slow.
  1214. if (this is ICollectionFolder)
  1215. {
  1216. return false;
  1217. }
  1218. if (this is UserView)
  1219. {
  1220. return false;
  1221. }
  1222. if (this is UserRootFolder)
  1223. {
  1224. return false;
  1225. }
  1226. if (this is Channel)
  1227. {
  1228. return false;
  1229. }
  1230. if (SourceType != SourceType.Library)
  1231. {
  1232. return false;
  1233. }
  1234. var iItemByName = this as IItemByName;
  1235. if (iItemByName != null)
  1236. {
  1237. var hasDualAccess = this as IHasDualAccess;
  1238. if (hasDualAccess == null || hasDualAccess.IsAccessedByName)
  1239. {
  1240. return false;
  1241. }
  1242. }
  1243. return true;
  1244. }
  1245. }
  1246. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, List<ItemFields> fields)
  1247. {
  1248. if (!SupportsUserDataFromChildren)
  1249. {
  1250. return;
  1251. }
  1252. if (itemDto != null)
  1253. {
  1254. if (fields.Contains(ItemFields.RecursiveItemCount))
  1255. {
  1256. itemDto.RecursiveItemCount = GetRecursiveChildCount(user);
  1257. }
  1258. }
  1259. if (SupportsPlayedStatus)
  1260. {
  1261. var unplayedQueryResult = GetItems(new InternalItemsQuery(user)
  1262. {
  1263. Recursive = true,
  1264. IsFolder = false,
  1265. IsVirtualItem = false,
  1266. EnableTotalRecordCount = true,
  1267. Limit = 0,
  1268. IsPlayed = false,
  1269. DtoOptions = new DtoOptions(false)
  1270. {
  1271. EnableImages = false
  1272. }
  1273. });
  1274. double unplayedCount = unplayedQueryResult.TotalRecordCount;
  1275. dto.UnplayedItemCount = unplayedQueryResult.TotalRecordCount;
  1276. if (itemDto != null && itemDto.RecursiveItemCount.HasValue)
  1277. {
  1278. if (itemDto.RecursiveItemCount.Value > 0)
  1279. {
  1280. var unplayedPercentage = (unplayedCount / itemDto.RecursiveItemCount.Value) * 100;
  1281. dto.PlayedPercentage = 100 - unplayedPercentage;
  1282. dto.Played = dto.PlayedPercentage.Value >= 100;
  1283. }
  1284. }
  1285. else
  1286. {
  1287. dto.Played = (dto.UnplayedItemCount ?? 0) == 0;
  1288. }
  1289. }
  1290. }
  1291. }
  1292. }