Folder.cs 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  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 currentChild.UpdateIsOffline(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 item.UpdateIsOffline(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 async Task RefreshMetadataRecursive(MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  393. {
  394. var children = ActualChildren.ToList();
  395. var percentages = new Dictionary<Guid, double>(children.Count);
  396. var numComplete = 0;
  397. var count = children.Count;
  398. foreach (var child in children)
  399. {
  400. cancellationToken.ThrowIfCancellationRequested();
  401. if (child.IsFolder)
  402. {
  403. var innerProgress = new ActionableProgress<double>();
  404. // Avoid implicitly captured closure
  405. var currentChild = child;
  406. innerProgress.RegisterAction(p =>
  407. {
  408. lock (percentages)
  409. {
  410. percentages[currentChild.Id] = p / 100;
  411. var innerPercent = percentages.Values.Sum();
  412. innerPercent /= count;
  413. innerPercent *= 100;
  414. progress.Report(innerPercent);
  415. }
  416. });
  417. await RefreshChildMetadata(child, refreshOptions, recursive, innerProgress, cancellationToken)
  418. .ConfigureAwait(false);
  419. }
  420. else
  421. {
  422. await RefreshChildMetadata(child, refreshOptions, false, new Progress<double>(), cancellationToken)
  423. .ConfigureAwait(false);
  424. }
  425. numComplete++;
  426. double percent = numComplete;
  427. percent /= count;
  428. percent *= 100;
  429. progress.Report(percent);
  430. }
  431. progress.Report(100);
  432. }
  433. private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  434. {
  435. var container = child as IMetadataContainer;
  436. if (container != null)
  437. {
  438. await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  439. }
  440. else
  441. {
  442. await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  443. if (recursive)
  444. {
  445. var folder = child as Folder;
  446. if (folder != null)
  447. {
  448. await folder.RefreshMetadataRecursive(refreshOptions, true, progress, cancellationToken);
  449. }
  450. }
  451. }
  452. progress.Report(100);
  453. }
  454. /// <summary>
  455. /// Refreshes the children.
  456. /// </summary>
  457. /// <param name="children">The children.</param>
  458. /// <param name="directoryService">The directory service.</param>
  459. /// <param name="progress">The progress.</param>
  460. /// <param name="cancellationToken">The cancellation token.</param>
  461. /// <returns>Task.</returns>
  462. private async Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
  463. {
  464. var list = children;
  465. var childCount = list.Count;
  466. var percentages = new Dictionary<Guid, double>(list.Count);
  467. foreach (var item in list)
  468. {
  469. cancellationToken.ThrowIfCancellationRequested();
  470. var child = item;
  471. var innerProgress = new ActionableProgress<double>();
  472. innerProgress.RegisterAction(p =>
  473. {
  474. lock (percentages)
  475. {
  476. percentages[child.Id] = p / 100;
  477. var percent = percentages.Values.Sum();
  478. percent /= childCount;
  479. progress.Report(10 * percent + 10);
  480. }
  481. });
  482. await child.ValidateChildrenInternal(innerProgress, cancellationToken, true, false, null, directoryService)
  483. .ConfigureAwait(false);
  484. }
  485. }
  486. /// <summary>
  487. /// Determines whether the specified path is offline.
  488. /// </summary>
  489. /// <param name="path">The path.</param>
  490. /// <returns><c>true</c> if the specified path is offline; otherwise, <c>false</c>.</returns>
  491. public static bool IsPathOffline(string path)
  492. {
  493. if (FileSystem.FileExists(path))
  494. {
  495. return false;
  496. }
  497. var originalPath = path;
  498. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  499. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  500. {
  501. if (FileSystem.DirectoryExists(path))
  502. {
  503. return false;
  504. }
  505. path = System.IO.Path.GetDirectoryName(path);
  506. }
  507. if (ContainsPath(LibraryManager.GetVirtualFolders(), originalPath))
  508. {
  509. return true;
  510. }
  511. return false;
  512. }
  513. /// <summary>
  514. /// Determines whether the specified folders contains path.
  515. /// </summary>
  516. /// <param name="folders">The folders.</param>
  517. /// <param name="path">The path.</param>
  518. /// <returns><c>true</c> if the specified folders contains path; otherwise, <c>false</c>.</returns>
  519. private static bool ContainsPath(IEnumerable<VirtualFolderInfo> folders, string path)
  520. {
  521. return folders.SelectMany(i => i.Locations).Any(i => ContainsPath(i, path));
  522. }
  523. private static bool ContainsPath(string parent, string path)
  524. {
  525. return string.Equals(parent, path, StringComparison.OrdinalIgnoreCase) || FileSystem.ContainsSubPath(parent, path);
  526. }
  527. /// <summary>
  528. /// Get the children of this folder from the actual file system
  529. /// </summary>
  530. /// <returns>IEnumerable{BaseItem}.</returns>
  531. protected virtual IEnumerable<BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
  532. {
  533. var collectionType = LibraryManager.GetContentType(this);
  534. var libraryOptions = LibraryManager.GetLibraryOptions(this);
  535. return LibraryManager.ResolvePaths(GetFileSystemChildren(directoryService), directoryService, this, libraryOptions, collectionType);
  536. }
  537. /// <summary>
  538. /// Get our children from the repo - stubbed for now
  539. /// </summary>
  540. /// <returns>IEnumerable{BaseItem}.</returns>
  541. protected IEnumerable<BaseItem> GetCachedChildren()
  542. {
  543. return ItemRepository.GetItemList(new InternalItemsQuery
  544. {
  545. ParentId = Id,
  546. GroupByPresentationUniqueKey = false
  547. });
  548. }
  549. public virtual int GetChildCount(User user)
  550. {
  551. if (LinkedChildren.Count > 0)
  552. {
  553. if (!(this is ICollectionFolder))
  554. {
  555. return GetChildren(user, true).Count();
  556. }
  557. }
  558. var result = GetItems(new InternalItemsQuery(user)
  559. {
  560. Recursive = false,
  561. Limit = 0,
  562. ParentId = Id
  563. }).Result;
  564. return result.TotalRecordCount;
  565. }
  566. public QueryResult<BaseItem> QueryRecursive(InternalItemsQuery query)
  567. {
  568. var user = query.User;
  569. if (!query.ForceDirect && RequiresPostFiltering(query))
  570. {
  571. IEnumerable<BaseItem> items;
  572. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  573. if (query.User == null)
  574. {
  575. items = GetRecursiveChildren(filter);
  576. }
  577. else
  578. {
  579. items = GetRecursiveChildren(user, query);
  580. }
  581. return PostFilterAndSort(items, query, true, true);
  582. }
  583. if (!(this is UserRootFolder) && !(this is AggregateFolder))
  584. {
  585. query.ParentId = query.ParentId ?? Id;
  586. }
  587. return LibraryManager.GetItemsResult(query);
  588. }
  589. private bool RequiresPostFiltering(InternalItemsQuery query)
  590. {
  591. if (LinkedChildren.Count > 0)
  592. {
  593. if (!(this is ICollectionFolder))
  594. {
  595. Logger.Debug("Query requires post-filtering due to LinkedChildren. Type: " + GetType().Name);
  596. return true;
  597. }
  598. }
  599. if (query.SortBy != null && query.SortBy.Length > 0)
  600. {
  601. if (query.SortBy.Contains(ItemSortBy.AiredEpisodeOrder, StringComparer.OrdinalIgnoreCase))
  602. {
  603. Logger.Debug("Query requires post-filtering due to ItemSortBy.AiredEpisodeOrder");
  604. return true;
  605. }
  606. if (query.SortBy.Contains(ItemSortBy.Budget, StringComparer.OrdinalIgnoreCase))
  607. {
  608. Logger.Debug("Query requires post-filtering due to ItemSortBy.Budget");
  609. return true;
  610. }
  611. if (query.SortBy.Contains(ItemSortBy.GameSystem, StringComparer.OrdinalIgnoreCase))
  612. {
  613. Logger.Debug("Query requires post-filtering due to ItemSortBy.GameSystem");
  614. return true;
  615. }
  616. if (query.SortBy.Contains(ItemSortBy.Metascore, StringComparer.OrdinalIgnoreCase))
  617. {
  618. Logger.Debug("Query requires post-filtering due to ItemSortBy.Metascore");
  619. return true;
  620. }
  621. if (query.SortBy.Contains(ItemSortBy.Players, StringComparer.OrdinalIgnoreCase))
  622. {
  623. Logger.Debug("Query requires post-filtering due to ItemSortBy.Players");
  624. return true;
  625. }
  626. if (query.SortBy.Contains(ItemSortBy.Revenue, StringComparer.OrdinalIgnoreCase))
  627. {
  628. Logger.Debug("Query requires post-filtering due to ItemSortBy.Revenue");
  629. return true;
  630. }
  631. if (query.SortBy.Contains(ItemSortBy.VideoBitRate, StringComparer.OrdinalIgnoreCase))
  632. {
  633. Logger.Debug("Query requires post-filtering due to ItemSortBy.VideoBitRate");
  634. return true;
  635. }
  636. }
  637. if (query.ItemIds.Length > 0)
  638. {
  639. Logger.Debug("Query requires post-filtering due to ItemIds");
  640. return true;
  641. }
  642. if (query.IsInBoxSet.HasValue)
  643. {
  644. Logger.Debug("Query requires post-filtering due to IsInBoxSet");
  645. return true;
  646. }
  647. // Filter by Video3DFormat
  648. if (query.Is3D.HasValue)
  649. {
  650. Logger.Debug("Query requires post-filtering due to Is3D");
  651. return true;
  652. }
  653. if (query.HasOfficialRating.HasValue)
  654. {
  655. Logger.Debug("Query requires post-filtering due to HasOfficialRating");
  656. return true;
  657. }
  658. if (query.IsPlaceHolder.HasValue)
  659. {
  660. Logger.Debug("Query requires post-filtering due to IsPlaceHolder");
  661. return true;
  662. }
  663. if (query.HasSpecialFeature.HasValue)
  664. {
  665. Logger.Debug("Query requires post-filtering due to HasSpecialFeature");
  666. return true;
  667. }
  668. if (query.HasSubtitles.HasValue)
  669. {
  670. Logger.Debug("Query requires post-filtering due to HasSubtitles");
  671. return true;
  672. }
  673. if (query.HasTrailer.HasValue)
  674. {
  675. Logger.Debug("Query requires post-filtering due to HasTrailer");
  676. return true;
  677. }
  678. if (query.HasThemeSong.HasValue)
  679. {
  680. Logger.Debug("Query requires post-filtering due to HasThemeSong");
  681. return true;
  682. }
  683. if (query.HasThemeVideo.HasValue)
  684. {
  685. Logger.Debug("Query requires post-filtering due to HasThemeVideo");
  686. return true;
  687. }
  688. // Filter by VideoType
  689. if (query.VideoTypes.Length > 0)
  690. {
  691. Logger.Debug("Query requires post-filtering due to VideoTypes");
  692. return true;
  693. }
  694. // Apply person filter
  695. if (query.ItemIdsFromPersonFilters != null)
  696. {
  697. Logger.Debug("Query requires post-filtering due to ItemIdsFromPersonFilters");
  698. return true;
  699. }
  700. if (query.MinPlayers.HasValue)
  701. {
  702. Logger.Debug("Query requires post-filtering due to MinPlayers");
  703. return true;
  704. }
  705. if (query.MaxPlayers.HasValue)
  706. {
  707. Logger.Debug("Query requires post-filtering due to MaxPlayers");
  708. return true;
  709. }
  710. if (UserViewBuilder.CollapseBoxSetItems(query, this, query.User, ConfigurationManager))
  711. {
  712. Logger.Debug("Query requires post-filtering due to CollapseBoxSetItems");
  713. return true;
  714. }
  715. if (!string.IsNullOrWhiteSpace(query.AdjacentTo))
  716. {
  717. Logger.Debug("Query requires post-filtering due to AdjacentTo");
  718. return true;
  719. }
  720. if (query.AirDays.Length > 0)
  721. {
  722. Logger.Debug("Query requires post-filtering due to AirDays");
  723. return true;
  724. }
  725. if (query.SeriesStatuses.Length > 0)
  726. {
  727. Logger.Debug("Query requires post-filtering due to SeriesStatuses");
  728. return true;
  729. }
  730. if (query.AiredDuringSeason.HasValue)
  731. {
  732. Logger.Debug("Query requires post-filtering due to AiredDuringSeason");
  733. return true;
  734. }
  735. if (!string.IsNullOrWhiteSpace(query.AlbumArtistStartsWithOrGreater))
  736. {
  737. Logger.Debug("Query requires post-filtering due to AlbumArtistStartsWithOrGreater");
  738. return true;
  739. }
  740. if (query.IsPlayed.HasValue)
  741. {
  742. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(typeof(Series).Name))
  743. {
  744. Logger.Debug("Query requires post-filtering due to IsPlayed");
  745. return true;
  746. }
  747. }
  748. return false;
  749. }
  750. public Task<QueryResult<BaseItem>> GetItems(InternalItemsQuery query)
  751. {
  752. if (query.ItemIds.Length > 0)
  753. {
  754. var result = LibraryManager.GetItemsResult(query);
  755. if (query.SortBy.Length == 0)
  756. {
  757. var ids = query.ItemIds.ToList();
  758. // Try to preserve order
  759. result.Items = result.Items.OrderBy(i => ids.IndexOf(i.Id.ToString("N"))).ToArray();
  760. }
  761. return Task.FromResult(result);
  762. }
  763. return GetItemsInternal(query);
  764. }
  765. protected virtual async Task<QueryResult<BaseItem>> GetItemsInternal(InternalItemsQuery query)
  766. {
  767. if (SourceType == SourceType.Channel)
  768. {
  769. try
  770. {
  771. // Don't blow up here because it could cause parent screens with other content to fail
  772. return await ChannelManager.GetChannelItemsInternal(new ChannelItemQuery
  773. {
  774. ChannelId = ChannelId,
  775. FolderId = Id.ToString("N"),
  776. Limit = query.Limit,
  777. StartIndex = query.StartIndex,
  778. UserId = query.User.Id.ToString("N"),
  779. SortBy = query.SortBy,
  780. SortOrder = query.SortOrder
  781. }, new Progress<double>(), CancellationToken.None);
  782. }
  783. catch
  784. {
  785. // Already logged at lower levels
  786. return new QueryResult<BaseItem>();
  787. }
  788. }
  789. if (query.Recursive)
  790. {
  791. return QueryRecursive(query);
  792. }
  793. var user = query.User;
  794. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  795. IEnumerable<BaseItem> items;
  796. if (query.User == null)
  797. {
  798. items = query.Recursive
  799. ? GetRecursiveChildren(filter)
  800. : Children.Where(filter);
  801. }
  802. else
  803. {
  804. items = query.Recursive
  805. ? GetRecursiveChildren(user, query)
  806. : GetChildren(user, true).Where(filter);
  807. }
  808. return PostFilterAndSort(items, query, true, true);
  809. }
  810. protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query, bool collapseBoxSetItems, bool enableSorting)
  811. {
  812. return UserViewBuilder.PostFilterAndSort(items, this, null, query, LibraryManager, ConfigurationManager, collapseBoxSetItems, enableSorting);
  813. }
  814. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  815. {
  816. if (user == null)
  817. {
  818. throw new ArgumentNullException();
  819. }
  820. //the true root should return our users root folder children
  821. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  822. var result = new Dictionary<Guid, BaseItem>();
  823. AddChildren(user, includeLinkedChildren, result, false, null);
  824. return result.Values;
  825. }
  826. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  827. {
  828. return Children;
  829. }
  830. /// <summary>
  831. /// Adds the children to list.
  832. /// </summary>
  833. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  834. private void AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, InternalItemsQuery query)
  835. {
  836. foreach (var child in GetEligibleChildrenForRecursiveChildren(user))
  837. {
  838. if (child.IsVisible(user))
  839. {
  840. if (query == null || UserViewBuilder.FilterItem(child, query))
  841. {
  842. result[child.Id] = child;
  843. }
  844. if (recursive && child.IsFolder)
  845. {
  846. var folder = (Folder)child;
  847. folder.AddChildren(user, includeLinkedChildren, result, true, query);
  848. }
  849. }
  850. }
  851. if (includeLinkedChildren)
  852. {
  853. foreach (var child in GetLinkedChildren(user))
  854. {
  855. if (child.IsVisible(user))
  856. {
  857. if (query == null || UserViewBuilder.FilterItem(child, query))
  858. {
  859. result[child.Id] = child;
  860. }
  861. }
  862. }
  863. }
  864. }
  865. /// <summary>
  866. /// Gets allowed recursive children of an item
  867. /// </summary>
  868. /// <param name="user">The user.</param>
  869. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  870. /// <returns>IEnumerable{BaseItem}.</returns>
  871. /// <exception cref="System.ArgumentNullException"></exception>
  872. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  873. {
  874. return GetRecursiveChildren(user, null);
  875. }
  876. public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query)
  877. {
  878. if (user == null)
  879. {
  880. throw new ArgumentNullException("user");
  881. }
  882. var result = new Dictionary<Guid, BaseItem>();
  883. AddChildren(user, true, result, true, query);
  884. return result.Values;
  885. }
  886. /// <summary>
  887. /// Gets the recursive children.
  888. /// </summary>
  889. /// <returns>IList{BaseItem}.</returns>
  890. public IList<BaseItem> GetRecursiveChildren()
  891. {
  892. return GetRecursiveChildren(true);
  893. }
  894. public IList<BaseItem> GetRecursiveChildren(bool includeLinkedChildren)
  895. {
  896. return GetRecursiveChildren(i => true, includeLinkedChildren);
  897. }
  898. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  899. {
  900. return GetRecursiveChildren(filter, true);
  901. }
  902. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter, bool includeLinkedChildren)
  903. {
  904. var result = new Dictionary<Guid, BaseItem>();
  905. AddChildrenToList(result, true, true, filter);
  906. return result.Values.ToList();
  907. }
  908. /// <summary>
  909. /// Adds the children to list.
  910. /// </summary>
  911. private void AddChildrenToList(Dictionary<Guid, BaseItem> result, bool includeLinkedChildren, bool recursive, Func<BaseItem, bool> filter)
  912. {
  913. foreach (var child in Children)
  914. {
  915. if (filter == null || filter(child))
  916. {
  917. result[child.Id] = child;
  918. }
  919. if (recursive && child.IsFolder)
  920. {
  921. var folder = (Folder)child;
  922. // We can only support includeLinkedChildren for the first folder, or we might end up stuck in a loop of linked items
  923. folder.AddChildrenToList(result, false, true, filter);
  924. }
  925. }
  926. if (includeLinkedChildren)
  927. {
  928. foreach (var child in GetLinkedChildren())
  929. {
  930. if (filter == null || filter(child))
  931. {
  932. result[child.Id] = child;
  933. }
  934. }
  935. }
  936. }
  937. /// <summary>
  938. /// Gets the linked children.
  939. /// </summary>
  940. /// <returns>IEnumerable{BaseItem}.</returns>
  941. public IEnumerable<BaseItem> GetLinkedChildren()
  942. {
  943. return LinkedChildren
  944. .Select(GetLinkedChild)
  945. .Where(i => i != null);
  946. }
  947. protected virtual bool FilterLinkedChildrenPerUser
  948. {
  949. get
  950. {
  951. return false;
  952. }
  953. }
  954. public IEnumerable<BaseItem> GetLinkedChildren(User user)
  955. {
  956. if (!FilterLinkedChildrenPerUser || user == null)
  957. {
  958. return GetLinkedChildren();
  959. }
  960. var locations = user.RootFolder
  961. .Children
  962. .OfType<CollectionFolder>()
  963. .Where(i => i.IsVisible(user))
  964. .SelectMany(i => i.PhysicalLocations)
  965. .ToList();
  966. return LinkedChildren
  967. .Select(i =>
  968. {
  969. var requiresPostFilter = true;
  970. if (!string.IsNullOrWhiteSpace(i.Path))
  971. {
  972. requiresPostFilter = false;
  973. if (!locations.Any(l => FileSystem.ContainsSubPath(l, i.Path)))
  974. {
  975. return null;
  976. }
  977. }
  978. var child = GetLinkedChild(i);
  979. if (requiresPostFilter && child != null)
  980. {
  981. if (string.IsNullOrWhiteSpace(child.Path))
  982. {
  983. Logger.Debug("Found LinkedChild with null path: {0}", child.Name);
  984. return child;
  985. }
  986. if (!locations.Any(l => FileSystem.ContainsSubPath(l, child.Path)))
  987. {
  988. return null;
  989. }
  990. }
  991. return child;
  992. })
  993. .Where(i => i != null);
  994. }
  995. /// <summary>
  996. /// Gets the linked children.
  997. /// </summary>
  998. /// <returns>IEnumerable{BaseItem}.</returns>
  999. public IEnumerable<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  1000. {
  1001. return LinkedChildren
  1002. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  1003. .Where(i => i.Item2 != null);
  1004. }
  1005. [IgnoreDataMember]
  1006. protected override bool SupportsOwnedItems
  1007. {
  1008. get
  1009. {
  1010. return base.SupportsOwnedItems || SupportsShortcutChildren;
  1011. }
  1012. }
  1013. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1014. {
  1015. var changesFound = false;
  1016. if (LocationType == LocationType.FileSystem)
  1017. {
  1018. if (RefreshLinkedChildren(fileSystemChildren))
  1019. {
  1020. changesFound = true;
  1021. }
  1022. }
  1023. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1024. return baseHasChanges || changesFound;
  1025. }
  1026. /// <summary>
  1027. /// Refreshes the linked children.
  1028. /// </summary>
  1029. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1030. private bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  1031. {
  1032. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  1033. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1034. List<LinkedChild> newShortcutLinks;
  1035. if (SupportsShortcutChildren)
  1036. {
  1037. newShortcutLinks = fileSystemChildren
  1038. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  1039. .Select(i =>
  1040. {
  1041. try
  1042. {
  1043. Logger.Debug("Found shortcut at {0}", i.FullName);
  1044. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  1045. if (!string.IsNullOrEmpty(resolvedPath))
  1046. {
  1047. return new LinkedChild
  1048. {
  1049. Path = resolvedPath,
  1050. Type = LinkedChildType.Shortcut
  1051. };
  1052. }
  1053. Logger.Error("Error resolving shortcut {0}", i.FullName);
  1054. return null;
  1055. }
  1056. catch (IOException ex)
  1057. {
  1058. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  1059. return null;
  1060. }
  1061. })
  1062. .Where(i => i != null)
  1063. .ToList();
  1064. }
  1065. else { newShortcutLinks = new List<LinkedChild>(); }
  1066. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  1067. {
  1068. Logger.Info("Shortcut links have changed for {0}", Path);
  1069. newShortcutLinks.AddRange(currentManualLinks);
  1070. LinkedChildren = newShortcutLinks;
  1071. return true;
  1072. }
  1073. foreach (var child in LinkedChildren)
  1074. {
  1075. // Reset the cached value
  1076. child.ItemId = null;
  1077. }
  1078. return false;
  1079. }
  1080. /// <summary>
  1081. /// Folders need to validate and refresh
  1082. /// </summary>
  1083. /// <returns>Task.</returns>
  1084. public override async Task ChangedExternally()
  1085. {
  1086. var progress = new Progress<double>();
  1087. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  1088. await base.ChangedExternally().ConfigureAwait(false);
  1089. }
  1090. /// <summary>
  1091. /// Marks the played.
  1092. /// </summary>
  1093. /// <param name="user">The user.</param>
  1094. /// <param name="datePlayed">The date played.</param>
  1095. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1096. /// <returns>Task.</returns>
  1097. public override async Task MarkPlayed(User user,
  1098. DateTime? datePlayed,
  1099. bool resetPosition)
  1100. {
  1101. var query = new InternalItemsQuery
  1102. {
  1103. User = user,
  1104. Recursive = true,
  1105. IsFolder = false,
  1106. EnableTotalRecordCount = false
  1107. };
  1108. if (!user.Configuration.DisplayMissingEpisodes || !user.Configuration.DisplayUnairedEpisodes)
  1109. {
  1110. query.ExcludeLocationTypes = new[] { LocationType.Virtual };
  1111. }
  1112. var itemsResult = await GetItems(query).ConfigureAwait(false);
  1113. // Sweep through recursively and update status
  1114. var tasks = itemsResult.Items.Select(c => c.MarkPlayed(user, datePlayed, resetPosition));
  1115. await Task.WhenAll(tasks).ConfigureAwait(false);
  1116. }
  1117. /// <summary>
  1118. /// Marks the unplayed.
  1119. /// </summary>
  1120. /// <param name="user">The user.</param>
  1121. /// <returns>Task.</returns>
  1122. public override async Task MarkUnplayed(User user)
  1123. {
  1124. var itemsResult = await GetItems(new InternalItemsQuery
  1125. {
  1126. User = user,
  1127. Recursive = true,
  1128. IsFolder = false,
  1129. EnableTotalRecordCount = false
  1130. }).ConfigureAwait(false);
  1131. // Sweep through recursively and update status
  1132. var tasks = itemsResult.Items.Select(c => c.MarkUnplayed(user));
  1133. await Task.WhenAll(tasks).ConfigureAwait(false);
  1134. }
  1135. public override bool IsPlayed(User user)
  1136. {
  1137. var itemsResult = GetItems(new InternalItemsQuery(user)
  1138. {
  1139. Recursive = true,
  1140. IsFolder = false,
  1141. ExcludeLocationTypes = new[] { LocationType.Virtual },
  1142. EnableTotalRecordCount = false
  1143. }).Result;
  1144. return itemsResult.Items
  1145. .All(i => i.IsPlayed(user));
  1146. }
  1147. public override bool IsUnplayed(User user)
  1148. {
  1149. return !IsPlayed(user);
  1150. }
  1151. [IgnoreDataMember]
  1152. public virtual bool SupportsUserDataFromChildren
  1153. {
  1154. get
  1155. {
  1156. // These are just far too slow.
  1157. if (this is ICollectionFolder)
  1158. {
  1159. return false;
  1160. }
  1161. if (this is UserView)
  1162. {
  1163. return false;
  1164. }
  1165. if (this is UserRootFolder)
  1166. {
  1167. return false;
  1168. }
  1169. if (this is Channel)
  1170. {
  1171. return false;
  1172. }
  1173. if (SourceType != SourceType.Library)
  1174. {
  1175. return false;
  1176. }
  1177. return true;
  1178. }
  1179. }
  1180. public override async Task FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user)
  1181. {
  1182. if (!SupportsUserDataFromChildren)
  1183. {
  1184. return;
  1185. }
  1186. var unplayedQueryResult = await GetItems(new InternalItemsQuery(user)
  1187. {
  1188. Recursive = true,
  1189. IsFolder = false,
  1190. IsVirtualItem = false,
  1191. EnableTotalRecordCount = true,
  1192. Limit = 0,
  1193. IsPlayed = false
  1194. }).ConfigureAwait(false);
  1195. var allItemsQueryResult = await GetItems(new InternalItemsQuery(user)
  1196. {
  1197. Recursive = true,
  1198. IsFolder = false,
  1199. IsVirtualItem = false,
  1200. EnableTotalRecordCount = true,
  1201. Limit = 0
  1202. }).ConfigureAwait(false);
  1203. if (itemDto != null)
  1204. {
  1205. itemDto.RecursiveItemCount = allItemsQueryResult.TotalRecordCount;
  1206. }
  1207. var recursiveItemCount = allItemsQueryResult.TotalRecordCount;
  1208. double unplayedCount = unplayedQueryResult.TotalRecordCount;
  1209. if (recursiveItemCount > 0)
  1210. {
  1211. var unplayedPercentage = (unplayedCount / recursiveItemCount) * 100;
  1212. dto.PlayedPercentage = 100 - unplayedPercentage;
  1213. dto.Played = dto.PlayedPercentage.Value >= 100;
  1214. dto.UnplayedItemCount = unplayedQueryResult.TotalRecordCount;
  1215. }
  1216. if (itemDto != null)
  1217. {
  1218. if (this is Season || this is MusicAlbum)
  1219. {
  1220. itemDto.ChildCount = recursiveItemCount;
  1221. }
  1222. }
  1223. }
  1224. }
  1225. }