Folder.cs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573
  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. protected override void TriggerOnRefreshStart()
  288. {
  289. }
  290. protected override void TriggerOnRefreshComplete()
  291. {
  292. }
  293. /// <summary>
  294. /// Validates the children internal.
  295. /// </summary>
  296. /// <param name="progress">The progress.</param>
  297. /// <param name="cancellationToken">The cancellation token.</param>
  298. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  299. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  300. /// <param name="refreshOptions">The refresh options.</param>
  301. /// <param name="directoryService">The directory service.</param>
  302. /// <returns>Task.</returns>
  303. protected virtual async Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  304. {
  305. if (recursive)
  306. {
  307. ProviderManager.OnRefreshStart(this);
  308. }
  309. try
  310. {
  311. await ValidateChildrenInternal2(progress, cancellationToken, recursive, refreshChildMetadata, refreshOptions, directoryService).ConfigureAwait(false);
  312. }
  313. finally
  314. {
  315. if (recursive)
  316. {
  317. ProviderManager.OnRefreshComplete(this);
  318. }
  319. }
  320. }
  321. private async Task ValidateChildrenInternal2(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  322. {
  323. var locationType = LocationType;
  324. cancellationToken.ThrowIfCancellationRequested();
  325. var validChildren = new List<BaseItem>();
  326. var validChildrenNeedGeneration = false;
  327. var allLibraryPaths = LibraryManager
  328. .GetVirtualFolders()
  329. .SelectMany(i => i.Locations)
  330. .ToList();
  331. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  332. {
  333. IEnumerable<BaseItem> nonCachedChildren;
  334. try
  335. {
  336. nonCachedChildren = GetNonCachedChildren(directoryService);
  337. }
  338. catch (IOException ex)
  339. {
  340. nonCachedChildren = new BaseItem[] { };
  341. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  342. }
  343. if (nonCachedChildren == null) return; //nothing to validate
  344. progress.Report(5);
  345. if (recursive)
  346. {
  347. ProviderManager.OnRefreshProgress(this, 5);
  348. }
  349. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  350. var currentChildren = GetActualChildrenDictionary();
  351. //create a list for our validated children
  352. var newItems = new List<BaseItem>();
  353. cancellationToken.ThrowIfCancellationRequested();
  354. foreach (var child in nonCachedChildren)
  355. {
  356. BaseItem currentChild;
  357. if (currentChildren.TryGetValue(child.Id, out currentChild))
  358. {
  359. validChildren.Add(currentChild);
  360. if (currentChild.UpdateFromResolvedItem(child) > ItemUpdateType.None)
  361. {
  362. currentChild.UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken);
  363. }
  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, this);
  400. }
  401. }
  402. LibraryManager.CreateItems(newItems, this, 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. }
  464. await RefreshMetadataRecursive(validChildren, refreshOptions, recursive, innerProgress, cancellationToken);
  465. }
  466. }
  467. }
  468. }
  469. private async Task RefreshMetadataRecursive(List<BaseItem> children, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  470. {
  471. var numComplete = 0;
  472. var count = children.Count;
  473. double currentPercent = 0;
  474. foreach (var child in children)
  475. {
  476. cancellationToken.ThrowIfCancellationRequested();
  477. using (var innerProgress = new ActionableProgress<double>())
  478. {
  479. // Avoid implicitly captured closure
  480. var currentInnerPercent = currentPercent;
  481. innerProgress.RegisterAction(p =>
  482. {
  483. double innerPercent = currentInnerPercent;
  484. innerPercent += p / (count);
  485. progress.Report(innerPercent);
  486. });
  487. await RefreshChildMetadata(child, refreshOptions, recursive && child.IsFolder, innerProgress, cancellationToken)
  488. .ConfigureAwait(false);
  489. }
  490. numComplete++;
  491. double percent = numComplete;
  492. percent /= count;
  493. percent *= 100;
  494. currentPercent = percent;
  495. progress.Report(percent);
  496. }
  497. }
  498. private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  499. {
  500. var container = child as IMetadataContainer;
  501. if (container != null)
  502. {
  503. await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  504. }
  505. else
  506. {
  507. if (refreshOptions.RefreshItem(child))
  508. {
  509. await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  510. }
  511. if (recursive)
  512. {
  513. var folder = child as Folder;
  514. if (folder != null)
  515. {
  516. await folder.RefreshMetadataRecursive(folder.Children.ToList(), refreshOptions, true, progress, cancellationToken);
  517. }
  518. }
  519. }
  520. }
  521. /// <summary>
  522. /// Refreshes the children.
  523. /// </summary>
  524. /// <param name="children">The children.</param>
  525. /// <param name="directoryService">The directory service.</param>
  526. /// <param name="progress">The progress.</param>
  527. /// <param name="cancellationToken">The cancellation token.</param>
  528. /// <returns>Task.</returns>
  529. private async Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
  530. {
  531. var numComplete = 0;
  532. var count = children.Count;
  533. double currentPercent = 0;
  534. foreach (var child in children)
  535. {
  536. cancellationToken.ThrowIfCancellationRequested();
  537. using (var innerProgress = new ActionableProgress<double>())
  538. {
  539. // Avoid implicitly captured closure
  540. var currentInnerPercent = currentPercent;
  541. innerProgress.RegisterAction(p =>
  542. {
  543. double innerPercent = currentInnerPercent;
  544. innerPercent += p / (count);
  545. progress.Report(innerPercent);
  546. });
  547. await child.ValidateChildrenInternal(innerProgress, cancellationToken, true, false, null, directoryService)
  548. .ConfigureAwait(false);
  549. }
  550. numComplete++;
  551. double percent = numComplete;
  552. percent /= count;
  553. percent *= 100;
  554. currentPercent = percent;
  555. progress.Report(percent);
  556. }
  557. }
  558. public static bool IsPathOffline(string path, List<string> allLibraryPaths)
  559. {
  560. //if (FileSystem.FileExists(path))
  561. //{
  562. // return false;
  563. //}
  564. var originalPath = path;
  565. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  566. while (!string.IsNullOrWhiteSpace(path) && path.Length > 1)
  567. {
  568. if (FileSystem.DirectoryExists(path))
  569. {
  570. return false;
  571. }
  572. if (allLibraryPaths.Contains(path, StringComparer.OrdinalIgnoreCase))
  573. {
  574. return true;
  575. }
  576. path = FileSystem.GetDirectoryName(path);
  577. }
  578. return allLibraryPaths.Any(i => ContainsPath(i, originalPath));
  579. }
  580. private static bool ContainsPath(string parent, string path)
  581. {
  582. return FileSystem.AreEqual(parent, path) || FileSystem.ContainsSubPath(parent, path);
  583. }
  584. /// <summary>
  585. /// Get the children of this folder from the actual file system
  586. /// </summary>
  587. /// <returns>IEnumerable{BaseItem}.</returns>
  588. protected virtual IEnumerable<BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
  589. {
  590. var collectionType = LibraryManager.GetContentType(this);
  591. var libraryOptions = LibraryManager.GetLibraryOptions(this);
  592. return LibraryManager.ResolvePaths(GetFileSystemChildren(directoryService), directoryService, this, libraryOptions, collectionType);
  593. }
  594. /// <summary>
  595. /// Get our children from the repo - stubbed for now
  596. /// </summary>
  597. /// <returns>IEnumerable{BaseItem}.</returns>
  598. protected List<BaseItem> GetCachedChildren()
  599. {
  600. return ItemRepository.GetItemList(new InternalItemsQuery
  601. {
  602. Parent = this,
  603. GroupByPresentationUniqueKey = false,
  604. DtoOptions = new DtoOptions(true)
  605. });
  606. }
  607. public virtual int GetChildCount(User user)
  608. {
  609. if (LinkedChildren.Length > 0)
  610. {
  611. if (!(this is ICollectionFolder))
  612. {
  613. return GetChildren(user, true).Count;
  614. }
  615. }
  616. var result = GetItems(new InternalItemsQuery(user)
  617. {
  618. Recursive = false,
  619. Limit = 0,
  620. Parent = this,
  621. DtoOptions = new DtoOptions(false)
  622. {
  623. EnableImages = false
  624. }
  625. });
  626. return result.TotalRecordCount;
  627. }
  628. public virtual int GetRecursiveChildCount(User user)
  629. {
  630. return GetItems(new InternalItemsQuery(user)
  631. {
  632. Recursive = true,
  633. IsFolder = false,
  634. IsVirtualItem = false,
  635. EnableTotalRecordCount = true,
  636. Limit = 0,
  637. DtoOptions = new DtoOptions(false)
  638. {
  639. EnableImages = false
  640. }
  641. }).TotalRecordCount;
  642. }
  643. public QueryResult<BaseItem> QueryRecursive(InternalItemsQuery query)
  644. {
  645. var user = query.User;
  646. if (!query.ForceDirect && RequiresPostFiltering(query))
  647. {
  648. IEnumerable<BaseItem> items;
  649. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  650. if (query.User == null)
  651. {
  652. items = GetRecursiveChildren(filter);
  653. }
  654. else
  655. {
  656. items = GetRecursiveChildren(user, query);
  657. }
  658. return PostFilterAndSort(items, query, true, true);
  659. }
  660. if (!(this is UserRootFolder) && !(this is AggregateFolder))
  661. {
  662. if (!query.ParentId.HasValue)
  663. {
  664. query.Parent = this;
  665. }
  666. }
  667. if (RequiresPostFiltering2(query))
  668. {
  669. return QueryWithPostFiltering2(query);
  670. }
  671. return LibraryManager.GetItemsResult(query);
  672. }
  673. private QueryResult<BaseItem> QueryWithPostFiltering2(InternalItemsQuery query)
  674. {
  675. var startIndex = query.StartIndex;
  676. var limit = query.Limit;
  677. query.StartIndex = null;
  678. query.Limit = null;
  679. var itemsList = LibraryManager.GetItemList(query);
  680. var user = query.User;
  681. if (user != null)
  682. {
  683. // needed for boxsets
  684. itemsList = itemsList.Where(i => i.IsVisibleStandalone(query.User)).ToList();
  685. }
  686. BaseItem[] returnItems;
  687. int totalCount = 0;
  688. if (query.EnableTotalRecordCount)
  689. {
  690. var itemsArray = itemsList.ToArray();
  691. totalCount = itemsArray.Length;
  692. returnItems = itemsArray;
  693. }
  694. else
  695. {
  696. returnItems = itemsList.ToArray();
  697. }
  698. if (limit.HasValue)
  699. {
  700. returnItems = returnItems.Skip(startIndex ?? 0).Take(limit.Value).ToArray();
  701. }
  702. else if (startIndex.HasValue)
  703. {
  704. returnItems = returnItems.Skip(startIndex.Value).ToArray();
  705. }
  706. return new QueryResult<BaseItem>
  707. {
  708. TotalRecordCount = totalCount,
  709. Items = returnItems.ToArray()
  710. };
  711. }
  712. private bool RequiresPostFiltering2(InternalItemsQuery query)
  713. {
  714. if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], typeof(BoxSet).Name, StringComparison.OrdinalIgnoreCase))
  715. {
  716. Logger.Debug("Query requires post-filtering due to BoxSet query");
  717. return true;
  718. }
  719. return false;
  720. }
  721. private bool RequiresPostFiltering(InternalItemsQuery query)
  722. {
  723. if (LinkedChildren.Length > 0)
  724. {
  725. if (!(this is ICollectionFolder))
  726. {
  727. Logger.Debug("Query requires post-filtering due to LinkedChildren. Type: " + GetType().Name);
  728. return true;
  729. }
  730. }
  731. if (query.IsInBoxSet.HasValue)
  732. {
  733. Logger.Debug("Query requires post-filtering due to IsInBoxSet");
  734. return true;
  735. }
  736. // Filter by Video3DFormat
  737. if (query.Is3D.HasValue)
  738. {
  739. Logger.Debug("Query requires post-filtering due to Is3D");
  740. return true;
  741. }
  742. if (query.HasOfficialRating.HasValue)
  743. {
  744. Logger.Debug("Query requires post-filtering due to HasOfficialRating");
  745. return true;
  746. }
  747. if (query.IsPlaceHolder.HasValue)
  748. {
  749. Logger.Debug("Query requires post-filtering due to IsPlaceHolder");
  750. return true;
  751. }
  752. if (query.HasSpecialFeature.HasValue)
  753. {
  754. Logger.Debug("Query requires post-filtering due to HasSpecialFeature");
  755. return true;
  756. }
  757. if (query.HasSubtitles.HasValue)
  758. {
  759. Logger.Debug("Query requires post-filtering due to HasSubtitles");
  760. return true;
  761. }
  762. if (query.HasTrailer.HasValue)
  763. {
  764. Logger.Debug("Query requires post-filtering due to HasTrailer");
  765. return true;
  766. }
  767. // Filter by VideoType
  768. if (query.VideoTypes.Length > 0)
  769. {
  770. Logger.Debug("Query requires post-filtering due to VideoTypes");
  771. return true;
  772. }
  773. // Apply person filter
  774. if (query.ItemIdsFromPersonFilters != null)
  775. {
  776. Logger.Debug("Query requires post-filtering due to ItemIdsFromPersonFilters");
  777. return true;
  778. }
  779. if (UserViewBuilder.CollapseBoxSetItems(query, this, query.User, ConfigurationManager))
  780. {
  781. Logger.Debug("Query requires post-filtering due to CollapseBoxSetItems");
  782. return true;
  783. }
  784. if (!string.IsNullOrWhiteSpace(query.AdjacentTo))
  785. {
  786. Logger.Debug("Query requires post-filtering due to AdjacentTo");
  787. return true;
  788. }
  789. if (query.SeriesStatuses.Length > 0)
  790. {
  791. Logger.Debug("Query requires post-filtering due to SeriesStatuses");
  792. return true;
  793. }
  794. if (query.AiredDuringSeason.HasValue)
  795. {
  796. Logger.Debug("Query requires post-filtering due to AiredDuringSeason");
  797. return true;
  798. }
  799. if (query.IsPlayed.HasValue)
  800. {
  801. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(typeof(Series).Name))
  802. {
  803. Logger.Debug("Query requires post-filtering due to IsPlayed");
  804. return true;
  805. }
  806. }
  807. return false;
  808. }
  809. public QueryResult<BaseItem> GetItems(InternalItemsQuery query)
  810. {
  811. if (query.ItemIds.Length > 0)
  812. {
  813. var result = LibraryManager.GetItemsResult(query);
  814. if (query.OrderBy.Length == 0)
  815. {
  816. var ids = query.ItemIds.ToList();
  817. // Try to preserve order
  818. result.Items = result.Items.OrderBy(i => ids.IndexOf(i.Id.ToString("N"))).ToArray();
  819. }
  820. return result;
  821. }
  822. return GetItemsInternal(query);
  823. }
  824. public BaseItem[] GetItemList(InternalItemsQuery query)
  825. {
  826. query.EnableTotalRecordCount = false;
  827. if (query.ItemIds.Length > 0)
  828. {
  829. var result = LibraryManager.GetItemList(query);
  830. if (query.OrderBy.Length == 0)
  831. {
  832. var ids = query.ItemIds.ToList();
  833. // Try to preserve order
  834. return result.OrderBy(i => ids.IndexOf(i.Id.ToString("N"))).ToArray();
  835. }
  836. return result.ToArray(result.Count);
  837. }
  838. return GetItemsInternal(query).Items;
  839. }
  840. protected virtual QueryResult<BaseItem> GetItemsInternal(InternalItemsQuery query)
  841. {
  842. if (SourceType == SourceType.Channel)
  843. {
  844. try
  845. {
  846. // Don't blow up here because it could cause parent screens with other content to fail
  847. return ChannelManager.GetChannelItemsInternal(new ChannelItemQuery
  848. {
  849. ChannelId = ChannelId,
  850. FolderId = Id.ToString("N"),
  851. Limit = query.Limit,
  852. StartIndex = query.StartIndex,
  853. UserId = query.User.Id.ToString("N"),
  854. OrderBy = query.OrderBy
  855. }, new SimpleProgress<double>(), CancellationToken.None).Result;
  856. }
  857. catch
  858. {
  859. // Already logged at lower levels
  860. return new QueryResult<BaseItem>();
  861. }
  862. }
  863. if (query.Recursive)
  864. {
  865. return QueryRecursive(query);
  866. }
  867. var user = query.User;
  868. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  869. IEnumerable<BaseItem> items;
  870. if (query.User == null)
  871. {
  872. items = query.Recursive
  873. ? GetRecursiveChildren(filter)
  874. : Children.Where(filter);
  875. }
  876. else
  877. {
  878. items = query.Recursive
  879. ? GetRecursiveChildren(user, query)
  880. : GetChildren(user, true).Where(filter);
  881. }
  882. return PostFilterAndSort(items, query, true, true);
  883. }
  884. protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query, bool collapseBoxSetItems, bool enableSorting)
  885. {
  886. return UserViewBuilder.PostFilterAndSort(items, this, null, query, LibraryManager, ConfigurationManager, collapseBoxSetItems, enableSorting);
  887. }
  888. public virtual List<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  889. {
  890. if (user == null)
  891. {
  892. throw new ArgumentNullException();
  893. }
  894. //the true root should return our users root folder children
  895. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  896. var result = new Dictionary<Guid, BaseItem>();
  897. AddChildren(user, includeLinkedChildren, result, false, null);
  898. return result.Values.ToList();
  899. }
  900. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  901. {
  902. return Children;
  903. }
  904. /// <summary>
  905. /// Adds the children to list.
  906. /// </summary>
  907. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  908. private void AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, InternalItemsQuery query)
  909. {
  910. foreach (var child in GetEligibleChildrenForRecursiveChildren(user))
  911. {
  912. if (child.IsVisible(user))
  913. {
  914. if (query == null || UserViewBuilder.FilterItem(child, query))
  915. {
  916. result[child.Id] = child;
  917. }
  918. if (recursive && child.IsFolder)
  919. {
  920. var folder = (Folder)child;
  921. folder.AddChildren(user, includeLinkedChildren, result, true, query);
  922. }
  923. }
  924. }
  925. if (includeLinkedChildren)
  926. {
  927. foreach (var child in GetLinkedChildren(user))
  928. {
  929. if (child.IsVisible(user))
  930. {
  931. if (query == null || UserViewBuilder.FilterItem(child, query))
  932. {
  933. result[child.Id] = child;
  934. }
  935. }
  936. }
  937. }
  938. }
  939. /// <summary>
  940. /// Gets allowed recursive children of an item
  941. /// </summary>
  942. /// <param name="user">The user.</param>
  943. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  944. /// <returns>IEnumerable{BaseItem}.</returns>
  945. /// <exception cref="System.ArgumentNullException"></exception>
  946. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  947. {
  948. return GetRecursiveChildren(user, null);
  949. }
  950. public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query)
  951. {
  952. if (user == null)
  953. {
  954. throw new ArgumentNullException("user");
  955. }
  956. var result = new Dictionary<Guid, BaseItem>();
  957. AddChildren(user, true, result, true, query);
  958. return result.Values;
  959. }
  960. /// <summary>
  961. /// Gets the recursive children.
  962. /// </summary>
  963. /// <returns>IList{BaseItem}.</returns>
  964. public IList<BaseItem> GetRecursiveChildren()
  965. {
  966. return GetRecursiveChildren(true);
  967. }
  968. public IList<BaseItem> GetRecursiveChildren(bool includeLinkedChildren)
  969. {
  970. return GetRecursiveChildren(i => true, includeLinkedChildren);
  971. }
  972. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  973. {
  974. return GetRecursiveChildren(filter, true);
  975. }
  976. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter, bool includeLinkedChildren)
  977. {
  978. var result = new Dictionary<Guid, BaseItem>();
  979. AddChildrenToList(result, includeLinkedChildren, true, filter);
  980. return result.Values.ToList();
  981. }
  982. /// <summary>
  983. /// Adds the children to list.
  984. /// </summary>
  985. private void AddChildrenToList(Dictionary<Guid, BaseItem> result, bool includeLinkedChildren, bool recursive, Func<BaseItem, bool> filter)
  986. {
  987. foreach (var child in Children)
  988. {
  989. if (filter == null || filter(child))
  990. {
  991. result[child.Id] = child;
  992. }
  993. if (recursive && child.IsFolder)
  994. {
  995. var folder = (Folder)child;
  996. // We can only support includeLinkedChildren for the first folder, or we might end up stuck in a loop of linked items
  997. folder.AddChildrenToList(result, false, true, filter);
  998. }
  999. }
  1000. if (includeLinkedChildren)
  1001. {
  1002. foreach (var child in GetLinkedChildren())
  1003. {
  1004. if (filter == null || filter(child))
  1005. {
  1006. result[child.Id] = child;
  1007. }
  1008. }
  1009. }
  1010. }
  1011. /// <summary>
  1012. /// Gets the linked children.
  1013. /// </summary>
  1014. /// <returns>IEnumerable{BaseItem}.</returns>
  1015. public List<BaseItem> GetLinkedChildren()
  1016. {
  1017. var linkedChildren = LinkedChildren;
  1018. var list = new List<BaseItem>(linkedChildren.Length);
  1019. foreach (var i in linkedChildren)
  1020. {
  1021. var child = GetLinkedChild(i);
  1022. if (child != null)
  1023. {
  1024. list.Add(child);
  1025. }
  1026. }
  1027. return list;
  1028. }
  1029. protected virtual bool FilterLinkedChildrenPerUser
  1030. {
  1031. get
  1032. {
  1033. return false;
  1034. }
  1035. }
  1036. public List<BaseItem> GetLinkedChildren(User user)
  1037. {
  1038. if (!FilterLinkedChildrenPerUser || user == null)
  1039. {
  1040. return GetLinkedChildren();
  1041. }
  1042. var linkedChildren = LinkedChildren;
  1043. var list = new List<BaseItem>(linkedChildren.Length);
  1044. if (linkedChildren.Length == 0)
  1045. {
  1046. return list;
  1047. }
  1048. var allUserRootChildren = user.RootFolder.Children.OfType<Folder>().ToList();
  1049. var collectionFolderIds = allUserRootChildren
  1050. .OfType<CollectionFolder>()
  1051. .Where(i => i.IsVisible(user))
  1052. .Select(i => i.Id)
  1053. .ToList();
  1054. foreach (var i in linkedChildren)
  1055. {
  1056. var child = GetLinkedChild(i);
  1057. if (child == null)
  1058. {
  1059. continue;
  1060. }
  1061. var childOwner = child.IsOwnedItem ? (child.GetOwner() ?? child) : child;
  1062. if (childOwner != null && !(child is IItemByName))
  1063. {
  1064. var childLocationType = childOwner.LocationType;
  1065. if (childLocationType == LocationType.Remote || childLocationType == LocationType.Virtual)
  1066. {
  1067. if (!childOwner.IsVisibleStandalone(user))
  1068. {
  1069. continue;
  1070. }
  1071. }
  1072. else if (childLocationType == LocationType.FileSystem)
  1073. {
  1074. var itemCollectionFolderIds =
  1075. LibraryManager.GetCollectionFolders(childOwner, allUserRootChildren).Select(f => f.Id);
  1076. if (!itemCollectionFolderIds.Any(collectionFolderIds.Contains))
  1077. {
  1078. continue;
  1079. }
  1080. }
  1081. }
  1082. list.Add(child);
  1083. }
  1084. return list;
  1085. }
  1086. /// <summary>
  1087. /// Gets the linked children.
  1088. /// </summary>
  1089. /// <returns>IEnumerable{BaseItem}.</returns>
  1090. public IEnumerable<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  1091. {
  1092. return LinkedChildren
  1093. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  1094. .Where(i => i.Item2 != null);
  1095. }
  1096. [IgnoreDataMember]
  1097. protected override bool SupportsOwnedItems
  1098. {
  1099. get
  1100. {
  1101. return base.SupportsOwnedItems || SupportsShortcutChildren;
  1102. }
  1103. }
  1104. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1105. {
  1106. var changesFound = false;
  1107. if (LocationType == LocationType.FileSystem)
  1108. {
  1109. if (RefreshLinkedChildren(fileSystemChildren))
  1110. {
  1111. changesFound = true;
  1112. }
  1113. }
  1114. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1115. return baseHasChanges || changesFound;
  1116. }
  1117. /// <summary>
  1118. /// Refreshes the linked children.
  1119. /// </summary>
  1120. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1121. protected virtual bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  1122. {
  1123. if (SupportsShortcutChildren)
  1124. {
  1125. var newShortcutLinks = fileSystemChildren
  1126. .Where(i => !i.IsDirectory && FileSystem.IsShortcut(i.FullName))
  1127. .Select(i =>
  1128. {
  1129. try
  1130. {
  1131. Logger.Debug("Found shortcut at {0}", i.FullName);
  1132. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  1133. if (!string.IsNullOrEmpty(resolvedPath))
  1134. {
  1135. return new LinkedChild
  1136. {
  1137. Path = resolvedPath,
  1138. Type = LinkedChildType.Shortcut
  1139. };
  1140. }
  1141. Logger.Error("Error resolving shortcut {0}", i.FullName);
  1142. return null;
  1143. }
  1144. catch (IOException ex)
  1145. {
  1146. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  1147. return null;
  1148. }
  1149. })
  1150. .Where(i => i != null)
  1151. .ToList();
  1152. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1153. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer(FileSystem)))
  1154. {
  1155. Logger.Info("Shortcut links have changed for {0}", Path);
  1156. newShortcutLinks.AddRange(LinkedChildren.Where(i => i.Type == LinkedChildType.Manual));
  1157. LinkedChildren = newShortcutLinks.ToArray(newShortcutLinks.Count);
  1158. return true;
  1159. }
  1160. }
  1161. foreach (var child in LinkedChildren)
  1162. {
  1163. // Reset the cached value
  1164. child.ItemId = null;
  1165. }
  1166. return false;
  1167. }
  1168. /// <summary>
  1169. /// Marks the played.
  1170. /// </summary>
  1171. /// <param name="user">The user.</param>
  1172. /// <param name="datePlayed">The date played.</param>
  1173. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1174. /// <returns>Task.</returns>
  1175. public override void MarkPlayed(User user,
  1176. DateTime? datePlayed,
  1177. bool resetPosition)
  1178. {
  1179. var query = new InternalItemsQuery
  1180. {
  1181. User = user,
  1182. Recursive = true,
  1183. IsFolder = false,
  1184. EnableTotalRecordCount = false
  1185. };
  1186. if (!user.Configuration.DisplayMissingEpisodes)
  1187. {
  1188. query.IsVirtualItem = false;
  1189. }
  1190. var itemsResult = GetItemList(query);
  1191. // Sweep through recursively and update status
  1192. foreach (var item in itemsResult)
  1193. {
  1194. if (item.IsVirtualItem)
  1195. {
  1196. // The querying doesn't support virtual unaired
  1197. var episode = item as Episode;
  1198. if (episode != null && episode.IsUnaired)
  1199. {
  1200. continue;
  1201. }
  1202. }
  1203. item.MarkPlayed(user, datePlayed, resetPosition);
  1204. }
  1205. }
  1206. /// <summary>
  1207. /// Marks the unplayed.
  1208. /// </summary>
  1209. /// <param name="user">The user.</param>
  1210. /// <returns>Task.</returns>
  1211. public override void MarkUnplayed(User user)
  1212. {
  1213. var itemsResult = GetItemList(new InternalItemsQuery
  1214. {
  1215. User = user,
  1216. Recursive = true,
  1217. IsFolder = false,
  1218. EnableTotalRecordCount = false
  1219. });
  1220. // Sweep through recursively and update status
  1221. foreach (var item in itemsResult)
  1222. {
  1223. item.MarkUnplayed(user);
  1224. }
  1225. }
  1226. public override bool IsPlayed(User user)
  1227. {
  1228. var itemsResult = GetItemList(new InternalItemsQuery(user)
  1229. {
  1230. Recursive = true,
  1231. IsFolder = false,
  1232. IsVirtualItem = false,
  1233. EnableTotalRecordCount = false
  1234. });
  1235. return itemsResult
  1236. .All(i => i.IsPlayed(user));
  1237. }
  1238. public override bool IsUnplayed(User user)
  1239. {
  1240. return !IsPlayed(user);
  1241. }
  1242. [IgnoreDataMember]
  1243. public virtual bool SupportsUserDataFromChildren
  1244. {
  1245. get
  1246. {
  1247. // These are just far too slow.
  1248. if (this is ICollectionFolder)
  1249. {
  1250. return false;
  1251. }
  1252. if (this is UserView)
  1253. {
  1254. return false;
  1255. }
  1256. if (this is UserRootFolder)
  1257. {
  1258. return false;
  1259. }
  1260. if (this is Channel)
  1261. {
  1262. return false;
  1263. }
  1264. if (SourceType != SourceType.Library)
  1265. {
  1266. return false;
  1267. }
  1268. var iItemByName = this as IItemByName;
  1269. if (iItemByName != null)
  1270. {
  1271. var hasDualAccess = this as IHasDualAccess;
  1272. if (hasDualAccess == null || hasDualAccess.IsAccessedByName)
  1273. {
  1274. return false;
  1275. }
  1276. }
  1277. return true;
  1278. }
  1279. }
  1280. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, ItemFields[] fields)
  1281. {
  1282. if (!SupportsUserDataFromChildren)
  1283. {
  1284. return;
  1285. }
  1286. if (itemDto != null)
  1287. {
  1288. if (fields.Contains(ItemFields.RecursiveItemCount))
  1289. {
  1290. itemDto.RecursiveItemCount = GetRecursiveChildCount(user);
  1291. }
  1292. }
  1293. if (SupportsPlayedStatus)
  1294. {
  1295. var unplayedQueryResult = GetItems(new InternalItemsQuery(user)
  1296. {
  1297. Recursive = true,
  1298. IsFolder = false,
  1299. IsVirtualItem = false,
  1300. EnableTotalRecordCount = true,
  1301. Limit = 0,
  1302. IsPlayed = false,
  1303. DtoOptions = new DtoOptions(false)
  1304. {
  1305. EnableImages = false
  1306. }
  1307. });
  1308. double unplayedCount = unplayedQueryResult.TotalRecordCount;
  1309. dto.UnplayedItemCount = unplayedQueryResult.TotalRecordCount;
  1310. if (itemDto != null && itemDto.RecursiveItemCount.HasValue)
  1311. {
  1312. if (itemDto.RecursiveItemCount.Value > 0)
  1313. {
  1314. var unplayedPercentage = (unplayedCount / itemDto.RecursiveItemCount.Value) * 100;
  1315. dto.PlayedPercentage = 100 - unplayedPercentage;
  1316. dto.Played = dto.PlayedPercentage.Value >= 100;
  1317. }
  1318. }
  1319. else
  1320. {
  1321. dto.Played = (dto.UnplayedItemCount ?? 0) == 0;
  1322. }
  1323. }
  1324. }
  1325. }
  1326. }