Folder.cs 50 KB

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