Folder.cs 50 KB

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