Folder.cs 49 KB

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