2
0

Folder.cs 50 KB

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