Folder.cs 51 KB

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