Folder.cs 51 KB

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