Folder.cs 50 KB

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