Folder.cs 50 KB

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