Folder.cs 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801
  1. #nullable disable
  2. #pragma warning disable CA1002, CA1721, CA1819, CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Collections.Immutable;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Security;
  9. using System.Text.Json.Serialization;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using J2N.Collections.Generic.Extensions;
  13. using Jellyfin.Data;
  14. using Jellyfin.Data.Enums;
  15. using Jellyfin.Database.Implementations.Entities;
  16. using Jellyfin.Database.Implementations.Enums;
  17. using Jellyfin.Extensions;
  18. using MediaBrowser.Controller.Channels;
  19. using MediaBrowser.Controller.Collections;
  20. using MediaBrowser.Controller.Configuration;
  21. using MediaBrowser.Controller.Dto;
  22. using MediaBrowser.Controller.Entities.Audio;
  23. using MediaBrowser.Controller.Entities.Movies;
  24. using MediaBrowser.Controller.Library;
  25. using MediaBrowser.Controller.LibraryTaskScheduler;
  26. using MediaBrowser.Controller.Providers;
  27. using MediaBrowser.Model.Dto;
  28. using MediaBrowser.Model.IO;
  29. using MediaBrowser.Model.Querying;
  30. using Microsoft.Extensions.Logging;
  31. using Episode = MediaBrowser.Controller.Entities.TV.Episode;
  32. using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
  33. using Season = MediaBrowser.Controller.Entities.TV.Season;
  34. using Series = MediaBrowser.Controller.Entities.TV.Series;
  35. namespace MediaBrowser.Controller.Entities
  36. {
  37. /// <summary>
  38. /// Class Folder.
  39. /// </summary>
  40. public class Folder : BaseItem
  41. {
  42. private IEnumerable<BaseItem> _children;
  43. public Folder()
  44. {
  45. LinkedChildren = Array.Empty<LinkedChild>();
  46. }
  47. public static IUserViewManager UserViewManager { get; set; }
  48. public static ILimitedConcurrencyLibraryScheduler LimitedConcurrencyLibraryScheduler { get; set; }
  49. /// <summary>
  50. /// Gets or sets a value indicating whether this instance is root.
  51. /// </summary>
  52. /// <value><c>true</c> if this instance is root; otherwise, <c>false</c>.</value>
  53. public bool IsRoot { get; set; }
  54. public LinkedChild[] LinkedChildren { get; set; }
  55. [JsonIgnore]
  56. public DateTime? DateLastMediaAdded { get; set; }
  57. [JsonIgnore]
  58. public override bool SupportsThemeMedia => true;
  59. [JsonIgnore]
  60. public virtual bool IsPreSorted => false;
  61. [JsonIgnore]
  62. public virtual bool IsPhysicalRoot => false;
  63. [JsonIgnore]
  64. public override bool SupportsInheritedParentImages => true;
  65. [JsonIgnore]
  66. public override bool SupportsPlayedStatus => true;
  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. [JsonIgnore]
  72. public override bool IsFolder => true;
  73. [JsonIgnore]
  74. public override bool IsDisplayedAsFolder => true;
  75. [JsonIgnore]
  76. public virtual bool SupportsCumulativeRunTimeTicks => false;
  77. [JsonIgnore]
  78. public virtual bool SupportsDateLastMediaAdded => false;
  79. [JsonIgnore]
  80. public override string FileNameWithoutExtension
  81. {
  82. get
  83. {
  84. if (IsFileProtocol)
  85. {
  86. return System.IO.Path.GetFileName(Path);
  87. }
  88. return null;
  89. }
  90. }
  91. /// <summary>
  92. /// Gets or Sets the actual children.
  93. /// </summary>
  94. /// <value>The actual children.</value>
  95. [JsonIgnore]
  96. public virtual IEnumerable<BaseItem> Children
  97. {
  98. get => _children ??= LoadChildren();
  99. set => _children = value;
  100. }
  101. /// <summary>
  102. /// Gets thread-safe access to all recursive children of this folder - without regard to user.
  103. /// </summary>
  104. /// <value>The recursive children.</value>
  105. [JsonIgnore]
  106. public IEnumerable<BaseItem> RecursiveChildren => GetRecursiveChildren();
  107. [JsonIgnore]
  108. protected virtual bool SupportsShortcutChildren => false;
  109. protected virtual bool FilterLinkedChildrenPerUser => false;
  110. [JsonIgnore]
  111. protected override bool SupportsOwnedItems => base.SupportsOwnedItems || SupportsShortcutChildren;
  112. [JsonIgnore]
  113. public virtual bool SupportsUserDataFromChildren
  114. {
  115. get
  116. {
  117. // These are just far too slow.
  118. if (this is ICollectionFolder)
  119. {
  120. return false;
  121. }
  122. if (this is UserView)
  123. {
  124. return false;
  125. }
  126. if (this is UserRootFolder)
  127. {
  128. return false;
  129. }
  130. if (this is Channel)
  131. {
  132. return false;
  133. }
  134. if (SourceType != SourceType.Library)
  135. {
  136. return false;
  137. }
  138. if (this is IItemByName)
  139. {
  140. if (this is not IHasDualAccess hasDualAccess || hasDualAccess.IsAccessedByName)
  141. {
  142. return false;
  143. }
  144. }
  145. return true;
  146. }
  147. }
  148. public static ICollectionManager CollectionManager { get; set; }
  149. public override bool CanDelete()
  150. {
  151. if (IsRoot)
  152. {
  153. return false;
  154. }
  155. return base.CanDelete();
  156. }
  157. public override bool RequiresRefresh()
  158. {
  159. var baseResult = base.RequiresRefresh();
  160. if (SupportsCumulativeRunTimeTicks && !RunTimeTicks.HasValue)
  161. {
  162. baseResult = true;
  163. }
  164. return baseResult;
  165. }
  166. /// <summary>
  167. /// Adds the child.
  168. /// </summary>
  169. /// <param name="item">The item.</param>
  170. /// <exception cref="InvalidOperationException">Unable to add + item.Name.</exception>
  171. public void AddChild(BaseItem item)
  172. {
  173. item.SetParent(this);
  174. if (item.Id.IsEmpty())
  175. {
  176. item.Id = LibraryManager.GetNewItemId(item.Path, item.GetType());
  177. }
  178. if (item.DateCreated == DateTime.MinValue)
  179. {
  180. item.DateCreated = DateTime.UtcNow;
  181. }
  182. if (item.DateModified == DateTime.MinValue)
  183. {
  184. item.DateModified = DateTime.UtcNow;
  185. }
  186. LibraryManager.CreateItem(item, this);
  187. }
  188. public override bool IsVisible(User user, bool skipAllowedTagsCheck = false)
  189. {
  190. if (this is ICollectionFolder && this is not BasePluginFolder)
  191. {
  192. var blockedMediaFolders = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedMediaFolders);
  193. if (blockedMediaFolders.Length > 0)
  194. {
  195. if (blockedMediaFolders.Contains(Id))
  196. {
  197. return false;
  198. }
  199. }
  200. else
  201. {
  202. if (!user.HasPermission(PermissionKind.EnableAllFolders)
  203. && !user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders).Contains(Id))
  204. {
  205. return false;
  206. }
  207. }
  208. }
  209. return base.IsVisible(user, skipAllowedTagsCheck);
  210. }
  211. /// <summary>
  212. /// Loads our children. Validation will occur externally.
  213. /// We want this synchronous.
  214. /// </summary>
  215. /// <returns>Returns children.</returns>
  216. protected virtual IReadOnlyList<BaseItem> LoadChildren()
  217. {
  218. // logger.LogDebug("Loading children from {0} {1} {2}", GetType().Name, Id, Path);
  219. // just load our children from the repo - the library will be validated and maintained in other processes
  220. return GetCachedChildren();
  221. }
  222. public override double? GetRefreshProgress()
  223. {
  224. return ProviderManager.GetRefreshProgress(Id);
  225. }
  226. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken)
  227. {
  228. return ValidateChildren(progress, new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken: cancellationToken);
  229. }
  230. /// <summary>
  231. /// Validates that the children of the folder still exist.
  232. /// </summary>
  233. /// <param name="progress">The progress.</param>
  234. /// <param name="metadataRefreshOptions">The metadata refresh options.</param>
  235. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  236. /// <param name="allowRemoveRoot">remove item even this folder is root.</param>
  237. /// <param name="cancellationToken">The cancellation token.</param>
  238. /// <returns>Task.</returns>
  239. public Task ValidateChildren(IProgress<double> progress, MetadataRefreshOptions metadataRefreshOptions, bool recursive = true, bool allowRemoveRoot = false, CancellationToken cancellationToken = default)
  240. {
  241. Children = null; // invalidate cached children.
  242. return ValidateChildrenInternal(progress, recursive, true, allowRemoveRoot, metadataRefreshOptions, metadataRefreshOptions.DirectoryService, cancellationToken);
  243. }
  244. private Dictionary<Guid, BaseItem> GetActualChildrenDictionary()
  245. {
  246. var dictionary = new Dictionary<Guid, BaseItem>();
  247. Children = null; // invalidate cached children.
  248. var childrenList = Children.ToList();
  249. foreach (var child in childrenList)
  250. {
  251. var id = child.Id;
  252. if (dictionary.ContainsKey(id))
  253. {
  254. Logger.LogError(
  255. "Found folder containing items with duplicate id. Path: {Path}, Child Name: {ChildName}",
  256. Path ?? Name,
  257. child.Path ?? child.Name);
  258. }
  259. else
  260. {
  261. dictionary[id] = child;
  262. }
  263. }
  264. return dictionary;
  265. }
  266. /// <summary>
  267. /// Validates the children internal.
  268. /// </summary>
  269. /// <param name="progress">The progress.</param>
  270. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  271. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  272. /// <param name="allowRemoveRoot">remove item even this folder is root.</param>
  273. /// <param name="refreshOptions">The refresh options.</param>
  274. /// <param name="directoryService">The directory service.</param>
  275. /// <param name="cancellationToken">The cancellation token.</param>
  276. /// <returns>Task.</returns>
  277. protected virtual async Task ValidateChildrenInternal(IProgress<double> progress, bool recursive, bool refreshChildMetadata, bool allowRemoveRoot, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService, CancellationToken cancellationToken)
  278. {
  279. if (recursive)
  280. {
  281. ProviderManager.OnRefreshStart(this);
  282. }
  283. try
  284. {
  285. await ValidateChildrenInternal2(progress, recursive, refreshChildMetadata, allowRemoveRoot, refreshOptions, directoryService, cancellationToken).ConfigureAwait(false);
  286. }
  287. finally
  288. {
  289. if (recursive)
  290. {
  291. ProviderManager.OnRefreshComplete(this);
  292. }
  293. }
  294. }
  295. private static bool IsLibraryFolderAccessible(IDirectoryService directoryService, BaseItem item, bool checkCollection)
  296. {
  297. if (!checkCollection && (item is BoxSet || string.Equals(item.FileNameWithoutExtension, "collections", StringComparison.OrdinalIgnoreCase)))
  298. {
  299. return true;
  300. }
  301. // For top parents i.e. Library folders, skip the validation if it's empty or inaccessible
  302. if (item.IsTopParent && !directoryService.IsAccessible(item.ContainingFolderPath))
  303. {
  304. Logger.LogWarning("Library folder {LibraryFolderPath} is inaccessible or empty, skipping", item.ContainingFolderPath);
  305. return false;
  306. }
  307. return true;
  308. }
  309. private async Task ValidateChildrenInternal2(IProgress<double> progress, bool recursive, bool refreshChildMetadata, bool allowRemoveRoot, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService, CancellationToken cancellationToken)
  310. {
  311. if (!IsLibraryFolderAccessible(directoryService, this, allowRemoveRoot))
  312. {
  313. return;
  314. }
  315. cancellationToken.ThrowIfCancellationRequested();
  316. var validChildren = new List<BaseItem>();
  317. var validChildrenNeedGeneration = false;
  318. if (IsFileProtocol)
  319. {
  320. IEnumerable<BaseItem> nonCachedChildren = [];
  321. try
  322. {
  323. nonCachedChildren = GetNonCachedChildren(directoryService);
  324. }
  325. catch (IOException ex)
  326. {
  327. Logger.LogError(ex, "Error retrieving children from file system");
  328. }
  329. catch (SecurityException ex)
  330. {
  331. Logger.LogError(ex, "Error retrieving children from file system");
  332. }
  333. catch (Exception ex)
  334. {
  335. Logger.LogError(ex, "Error retrieving children");
  336. return;
  337. }
  338. progress.Report(ProgressHelpers.RetrievedChildren);
  339. if (recursive)
  340. {
  341. ProviderManager.OnRefreshProgress(this, ProgressHelpers.RetrievedChildren);
  342. }
  343. // Build a dictionary of the current children we have now by Id so we can compare quickly and easily
  344. var currentChildren = GetActualChildrenDictionary();
  345. // Create a list for our validated children
  346. var newItems = new List<BaseItem>();
  347. cancellationToken.ThrowIfCancellationRequested();
  348. foreach (var child in nonCachedChildren)
  349. {
  350. if (!IsLibraryFolderAccessible(directoryService, child, allowRemoveRoot))
  351. {
  352. continue;
  353. }
  354. if (currentChildren.TryGetValue(child.Id, out BaseItem currentChild))
  355. {
  356. validChildren.Add(currentChild);
  357. if (currentChild.UpdateFromResolvedItem(child) > ItemUpdateType.None)
  358. {
  359. await currentChild.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  360. }
  361. else
  362. {
  363. // metadata is up-to-date; make sure DB has correct images dimensions and hash
  364. await LibraryManager.UpdateImagesAsync(currentChild).ConfigureAwait(false);
  365. }
  366. continue;
  367. }
  368. // Brand new item - needs to be added
  369. child.SetParent(this);
  370. newItems.Add(child);
  371. validChildren.Add(child);
  372. }
  373. // That's all the new and changed ones - now see if any have been removed and need cleanup
  374. var itemsRemoved = currentChildren.Values.Except(validChildren).ToList();
  375. var shouldRemove = !IsRoot || allowRemoveRoot;
  376. // If it's an AggregateFolder, don't remove
  377. if (shouldRemove && itemsRemoved.Count > 0)
  378. {
  379. foreach (var item in itemsRemoved)
  380. {
  381. if (item.IsFileProtocol)
  382. {
  383. Logger.LogDebug("Removed item: {Path}", item.Path);
  384. item.SetParent(null);
  385. LibraryManager.DeleteItem(item, new DeleteOptions { DeleteFileLocation = false }, this, false);
  386. }
  387. }
  388. }
  389. if (newItems.Count > 0)
  390. {
  391. LibraryManager.CreateItems(newItems, this, cancellationToken);
  392. }
  393. }
  394. else
  395. {
  396. validChildrenNeedGeneration = true;
  397. }
  398. progress.Report(ProgressHelpers.UpdatedChildItems);
  399. if (recursive)
  400. {
  401. ProviderManager.OnRefreshProgress(this, ProgressHelpers.UpdatedChildItems);
  402. }
  403. cancellationToken.ThrowIfCancellationRequested();
  404. if (recursive)
  405. {
  406. var folder = this;
  407. var innerProgress = new Progress<double>(innerPercent =>
  408. {
  409. var percent = ProgressHelpers.GetProgress(ProgressHelpers.UpdatedChildItems, ProgressHelpers.ScannedSubfolders, innerPercent);
  410. progress.Report(percent);
  411. ProviderManager.OnRefreshProgress(folder, percent);
  412. });
  413. if (validChildrenNeedGeneration)
  414. {
  415. validChildren = Children.ToList();
  416. validChildrenNeedGeneration = false;
  417. }
  418. await ValidateSubFolders(validChildren.OfType<Folder>().ToList(), directoryService, innerProgress, cancellationToken).ConfigureAwait(false);
  419. }
  420. if (refreshChildMetadata)
  421. {
  422. progress.Report(ProgressHelpers.ScannedSubfolders);
  423. if (recursive)
  424. {
  425. ProviderManager.OnRefreshProgress(this, ProgressHelpers.ScannedSubfolders);
  426. }
  427. var container = this as IMetadataContainer;
  428. var folder = this;
  429. var innerProgress = new Progress<double>(innerPercent =>
  430. {
  431. var percent = ProgressHelpers.GetProgress(ProgressHelpers.ScannedSubfolders, ProgressHelpers.RefreshedMetadata, innerPercent);
  432. progress.Report(percent);
  433. if (recursive)
  434. {
  435. ProviderManager.OnRefreshProgress(folder, percent);
  436. }
  437. });
  438. if (container is not null)
  439. {
  440. await RefreshAllMetadataForContainer(container, refreshOptions, innerProgress, cancellationToken).ConfigureAwait(false);
  441. }
  442. else
  443. {
  444. if (validChildrenNeedGeneration)
  445. {
  446. Children = null; // invalidate cached children.
  447. validChildren = Children.ToList();
  448. }
  449. await RefreshMetadataRecursive(validChildren, refreshOptions, recursive, innerProgress, cancellationToken).ConfigureAwait(false);
  450. }
  451. }
  452. }
  453. private async Task RefreshMetadataRecursive(IList<BaseItem> children, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  454. {
  455. await RunTasks(
  456. (baseItem, innerProgress) => RefreshChildMetadata(baseItem, refreshOptions, recursive && baseItem.IsFolder, innerProgress, cancellationToken),
  457. children,
  458. progress,
  459. cancellationToken).ConfigureAwait(false);
  460. }
  461. private async Task RefreshAllMetadataForContainer(IMetadataContainer container, MetadataRefreshOptions refreshOptions, IProgress<double> progress, CancellationToken cancellationToken)
  462. {
  463. if (container is Series series)
  464. {
  465. await series.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  466. }
  467. await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  468. }
  469. private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  470. {
  471. if (child is IMetadataContainer container)
  472. {
  473. await RefreshAllMetadataForContainer(container, refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  474. }
  475. else
  476. {
  477. if (refreshOptions.RefreshItem(child))
  478. {
  479. await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  480. }
  481. if (recursive && child is Folder folder)
  482. {
  483. folder.Children = null; // invalidate cached children.
  484. await folder.RefreshMetadataRecursive(folder.Children.Except([this, child]).ToList(), refreshOptions, true, progress, cancellationToken).ConfigureAwait(false);
  485. }
  486. }
  487. }
  488. /// <summary>
  489. /// Refreshes the children.
  490. /// </summary>
  491. /// <param name="children">The children.</param>
  492. /// <param name="directoryService">The directory service.</param>
  493. /// <param name="progress">The progress.</param>
  494. /// <param name="cancellationToken">The cancellation token.</param>
  495. /// <returns>Task.</returns>
  496. private async Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
  497. {
  498. await RunTasks(
  499. (folder, innerProgress) => folder.ValidateChildrenInternal(innerProgress, true, false, false, null, directoryService, cancellationToken),
  500. children,
  501. progress,
  502. cancellationToken).ConfigureAwait(false);
  503. }
  504. /// <summary>
  505. /// Runs an action block on a list of children.
  506. /// </summary>
  507. /// <param name="task">The task to run for each child.</param>
  508. /// <param name="children">The list of children.</param>
  509. /// <param name="progress">The progress.</param>
  510. /// <param name="cancellationToken">The cancellation token.</param>
  511. /// <returns>Task.</returns>
  512. private async Task RunTasks<T>(Func<T, IProgress<double>, Task> task, IList<T> children, IProgress<double> progress, CancellationToken cancellationToken)
  513. {
  514. await LimitedConcurrencyLibraryScheduler
  515. .Enqueue(
  516. children.ToArray(),
  517. task,
  518. progress,
  519. cancellationToken)
  520. .ConfigureAwait(false);
  521. }
  522. /// <summary>
  523. /// Get the children of this folder from the actual file system.
  524. /// </summary>
  525. /// <returns>IEnumerable{BaseItem}.</returns>
  526. /// <param name="directoryService">The directory service to use for operation.</param>
  527. /// <returns>Returns set of base items.</returns>
  528. protected virtual IEnumerable<BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
  529. {
  530. var collectionType = LibraryManager.GetContentType(this);
  531. var libraryOptions = LibraryManager.GetLibraryOptions(this);
  532. return LibraryManager.ResolvePaths(GetFileSystemChildren(directoryService), directoryService, this, libraryOptions, collectionType);
  533. }
  534. /// <summary>
  535. /// Get our children from the repo - stubbed for now.
  536. /// </summary>
  537. /// <returns>IEnumerable{BaseItem}.</returns>
  538. protected IReadOnlyList<BaseItem> GetCachedChildren()
  539. {
  540. return ItemRepository.GetItemList(new InternalItemsQuery
  541. {
  542. Parent = this,
  543. GroupByPresentationUniqueKey = false,
  544. DtoOptions = new DtoOptions(true)
  545. });
  546. }
  547. public virtual int GetChildCount(User user)
  548. {
  549. if (LinkedChildren.Length > 0)
  550. {
  551. if (this is not ICollectionFolder)
  552. {
  553. return GetChildren(user, true).Count;
  554. }
  555. }
  556. var result = GetItems(new InternalItemsQuery(user)
  557. {
  558. Recursive = false,
  559. Limit = 0,
  560. Parent = this,
  561. DtoOptions = new DtoOptions(false)
  562. {
  563. EnableImages = false
  564. }
  565. });
  566. return result.TotalRecordCount;
  567. }
  568. public virtual int GetRecursiveChildCount(User user)
  569. {
  570. return GetItems(new InternalItemsQuery(user)
  571. {
  572. Recursive = true,
  573. IsFolder = false,
  574. IsVirtualItem = false,
  575. EnableTotalRecordCount = true,
  576. Limit = 0,
  577. DtoOptions = new DtoOptions(false)
  578. {
  579. EnableImages = false
  580. }
  581. }).TotalRecordCount;
  582. }
  583. public QueryResult<BaseItem> QueryRecursive(InternalItemsQuery query)
  584. {
  585. var user = query.User;
  586. if (!query.ForceDirect && RequiresPostFiltering(query))
  587. {
  588. IEnumerable<BaseItem> items;
  589. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  590. var totalCount = 0;
  591. if (query.User is null)
  592. {
  593. items = GetRecursiveChildren(filter);
  594. totalCount = items.Count();
  595. }
  596. else
  597. {
  598. items = GetRecursiveChildren(user, query, out totalCount);
  599. query.Limit = null;
  600. query.StartIndex = null; // override these here as they have already been applied
  601. }
  602. var result = PostFilterAndSort(items, query);
  603. result.TotalRecordCount = totalCount;
  604. return result;
  605. }
  606. if (this is not UserRootFolder
  607. && this is not AggregateFolder
  608. && query.ParentId.IsEmpty())
  609. {
  610. query.Parent = this;
  611. }
  612. if (RequiresPostFiltering2(query))
  613. {
  614. return QueryWithPostFiltering2(query);
  615. }
  616. return LibraryManager.GetItemsResult(query);
  617. }
  618. protected QueryResult<BaseItem> QueryWithPostFiltering2(InternalItemsQuery query)
  619. {
  620. var startIndex = query.StartIndex;
  621. var limit = query.Limit;
  622. query.StartIndex = null;
  623. query.Limit = null;
  624. IEnumerable<BaseItem> itemsList = LibraryManager.GetItemList(query);
  625. var user = query.User;
  626. if (user is not null)
  627. {
  628. // needed for boxsets
  629. itemsList = itemsList.Where(i => i.IsVisibleStandalone(query.User));
  630. }
  631. IEnumerable<BaseItem> returnItems;
  632. int totalCount = 0;
  633. if (query.EnableTotalRecordCount)
  634. {
  635. var itemArray = itemsList.ToArray();
  636. totalCount = itemArray.Length;
  637. returnItems = itemArray;
  638. }
  639. else
  640. {
  641. returnItems = itemsList;
  642. }
  643. if (limit.HasValue)
  644. {
  645. returnItems = returnItems.Skip(startIndex ?? 0).Take(limit.Value);
  646. }
  647. else if (startIndex.HasValue)
  648. {
  649. returnItems = returnItems.Skip(startIndex.Value);
  650. }
  651. return new QueryResult<BaseItem>(
  652. query.StartIndex,
  653. totalCount,
  654. returnItems.ToArray());
  655. }
  656. private bool RequiresPostFiltering2(InternalItemsQuery query)
  657. {
  658. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes[0] == BaseItemKind.BoxSet)
  659. {
  660. Logger.LogDebug("Query requires post-filtering due to BoxSet query");
  661. return true;
  662. }
  663. return false;
  664. }
  665. private bool RequiresPostFiltering(InternalItemsQuery query)
  666. {
  667. if (LinkedChildren.Length > 0)
  668. {
  669. if (this is not ICollectionFolder)
  670. {
  671. Logger.LogDebug("{Type}: Query requires post-filtering due to LinkedChildren.", GetType().Name);
  672. return true;
  673. }
  674. }
  675. // Filter by Video3DFormat
  676. if (query.Is3D.HasValue)
  677. {
  678. Logger.LogDebug("Query requires post-filtering due to Is3D");
  679. return true;
  680. }
  681. if (query.HasOfficialRating.HasValue)
  682. {
  683. Logger.LogDebug("Query requires post-filtering due to HasOfficialRating");
  684. return true;
  685. }
  686. if (query.IsPlaceHolder.HasValue)
  687. {
  688. Logger.LogDebug("Query requires post-filtering due to IsPlaceHolder");
  689. return true;
  690. }
  691. if (query.HasSpecialFeature.HasValue)
  692. {
  693. Logger.LogDebug("Query requires post-filtering due to HasSpecialFeature");
  694. return true;
  695. }
  696. if (query.HasSubtitles.HasValue)
  697. {
  698. Logger.LogDebug("Query requires post-filtering due to HasSubtitles");
  699. return true;
  700. }
  701. if (query.HasTrailer.HasValue)
  702. {
  703. Logger.LogDebug("Query requires post-filtering due to HasTrailer");
  704. return true;
  705. }
  706. if (query.HasThemeSong.HasValue)
  707. {
  708. Logger.LogDebug("Query requires post-filtering due to HasThemeSong");
  709. return true;
  710. }
  711. if (query.HasThemeVideo.HasValue)
  712. {
  713. Logger.LogDebug("Query requires post-filtering due to HasThemeVideo");
  714. return true;
  715. }
  716. // Filter by VideoType
  717. if (query.VideoTypes.Length > 0)
  718. {
  719. Logger.LogDebug("Query requires post-filtering due to VideoTypes");
  720. return true;
  721. }
  722. if (CollapseBoxSetItems(query, this, query.User, ConfigurationManager))
  723. {
  724. Logger.LogDebug("Query requires post-filtering due to CollapseBoxSetItems");
  725. return true;
  726. }
  727. if (!query.AdjacentTo.IsNullOrEmpty())
  728. {
  729. Logger.LogDebug("Query requires post-filtering due to AdjacentTo");
  730. return true;
  731. }
  732. if (query.SeriesStatuses.Length > 0)
  733. {
  734. Logger.LogDebug("Query requires post-filtering due to SeriesStatuses");
  735. return true;
  736. }
  737. if (query.AiredDuringSeason.HasValue)
  738. {
  739. Logger.LogDebug("Query requires post-filtering due to AiredDuringSeason");
  740. return true;
  741. }
  742. if (query.IsPlayed.HasValue)
  743. {
  744. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(BaseItemKind.Series))
  745. {
  746. Logger.LogDebug("Query requires post-filtering due to IsPlayed");
  747. return true;
  748. }
  749. }
  750. return false;
  751. }
  752. private static BaseItem[] SortItemsByRequest(InternalItemsQuery query, IReadOnlyList<BaseItem> items)
  753. {
  754. return items.OrderBy(i => Array.IndexOf(query.ItemIds, i.Id)).ToArray();
  755. }
  756. public QueryResult<BaseItem> GetItems(InternalItemsQuery query)
  757. {
  758. if (query.ItemIds.Length > 0)
  759. {
  760. var result = LibraryManager.GetItemsResult(query);
  761. if (query.OrderBy.Count == 0 && query.ItemIds.Length > 1)
  762. {
  763. result.Items = SortItemsByRequest(query, result.Items);
  764. }
  765. return result;
  766. }
  767. return GetItemsInternal(query);
  768. }
  769. public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query)
  770. {
  771. query.EnableTotalRecordCount = false;
  772. if (query.ItemIds.Length > 0)
  773. {
  774. var result = LibraryManager.GetItemList(query);
  775. if (query.OrderBy.Count == 0 && query.ItemIds.Length > 1)
  776. {
  777. return SortItemsByRequest(query, result);
  778. }
  779. return result;
  780. }
  781. return GetItemsInternal(query).Items;
  782. }
  783. protected virtual QueryResult<BaseItem> GetItemsInternal(InternalItemsQuery query)
  784. {
  785. if (SourceType == SourceType.Channel)
  786. {
  787. try
  788. {
  789. query.Parent = this;
  790. query.ChannelIds = new[] { ChannelId };
  791. // Don't blow up here because it could cause parent screens with other content to fail
  792. return ChannelManager.GetChannelItemsInternal(query, new Progress<double>(), CancellationToken.None).GetAwaiter().GetResult();
  793. }
  794. catch
  795. {
  796. // Already logged at lower levels
  797. return new QueryResult<BaseItem>();
  798. }
  799. }
  800. if (query.Recursive)
  801. {
  802. return QueryRecursive(query);
  803. }
  804. var user = query.User;
  805. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  806. IEnumerable<BaseItem> items;
  807. int totalItemCount = 0;
  808. if (query.User is null)
  809. {
  810. items = Children.Where(filter);
  811. totalItemCount = items.Count();
  812. }
  813. else
  814. {
  815. // need to pass this param to the children.
  816. var childQuery = new InternalItemsQuery
  817. {
  818. DisplayAlbumFolders = query.DisplayAlbumFolders,
  819. Limit = query.Limit,
  820. StartIndex = query.StartIndex
  821. };
  822. items = GetChildren(user, true, out totalItemCount, childQuery).Where(filter);
  823. query.Limit = null;
  824. query.StartIndex = null;
  825. }
  826. var result = PostFilterAndSort(items, query);
  827. result.TotalRecordCount = totalItemCount;
  828. return result;
  829. }
  830. protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query)
  831. {
  832. var user = query.User;
  833. // Check recursive - don't substitute in plain folder views
  834. if (user is not null)
  835. {
  836. items = CollapseBoxSetItemsIfNeeded(items, query, this, user, ConfigurationManager, CollectionManager);
  837. }
  838. #pragma warning disable CA1309
  839. if (!string.IsNullOrEmpty(query.NameStartsWithOrGreater))
  840. {
  841. items = items.Where(i => string.Compare(query.NameStartsWithOrGreater, i.SortName, StringComparison.InvariantCultureIgnoreCase) < 1);
  842. }
  843. if (!string.IsNullOrEmpty(query.NameStartsWith))
  844. {
  845. items = items.Where(i => i.SortName.StartsWith(query.NameStartsWith, StringComparison.InvariantCultureIgnoreCase));
  846. }
  847. if (!string.IsNullOrEmpty(query.NameLessThan))
  848. {
  849. items = items.Where(i => string.Compare(query.NameLessThan, i.SortName, StringComparison.InvariantCultureIgnoreCase) == 1);
  850. }
  851. #pragma warning restore CA1309
  852. // This must be the last filter
  853. if (!query.AdjacentTo.IsNullOrEmpty())
  854. {
  855. items = UserViewBuilder.FilterForAdjacency(items.ToList(), query.AdjacentTo.Value);
  856. }
  857. return UserViewBuilder.SortAndPage(items, null, query, LibraryManager);
  858. }
  859. private static IEnumerable<BaseItem> CollapseBoxSetItemsIfNeeded(
  860. IEnumerable<BaseItem> items,
  861. InternalItemsQuery query,
  862. BaseItem queryParent,
  863. User user,
  864. IServerConfigurationManager configurationManager,
  865. ICollectionManager collectionManager)
  866. {
  867. ArgumentNullException.ThrowIfNull(items);
  868. if (CollapseBoxSetItems(query, queryParent, user, configurationManager))
  869. {
  870. items = collectionManager.CollapseItemsWithinBoxSets(items, user);
  871. }
  872. return items;
  873. }
  874. private static bool CollapseBoxSetItems(
  875. InternalItemsQuery query,
  876. BaseItem queryParent,
  877. User user,
  878. IServerConfigurationManager configurationManager)
  879. {
  880. // Could end up stuck in a loop like this
  881. if (queryParent is BoxSet)
  882. {
  883. return false;
  884. }
  885. if (queryParent is Season)
  886. {
  887. return false;
  888. }
  889. if (queryParent is MusicAlbum)
  890. {
  891. return false;
  892. }
  893. if (queryParent is MusicArtist)
  894. {
  895. return false;
  896. }
  897. var param = query.CollapseBoxSetItems;
  898. if (!param.HasValue)
  899. {
  900. if (user is not null && query.IncludeItemTypes.Any(type =>
  901. (type == BaseItemKind.Movie && !configurationManager.Configuration.EnableGroupingMoviesIntoCollections) ||
  902. (type == BaseItemKind.Series && !configurationManager.Configuration.EnableGroupingShowsIntoCollections)))
  903. {
  904. return false;
  905. }
  906. if (query.IncludeItemTypes.Length == 0
  907. || query.IncludeItemTypes.Any(type => type == BaseItemKind.Movie || type == BaseItemKind.Series))
  908. {
  909. param = true;
  910. }
  911. }
  912. return param.HasValue && param.Value && AllowBoxSetCollapsing(query);
  913. }
  914. private static bool AllowBoxSetCollapsing(InternalItemsQuery request)
  915. {
  916. if (request.IsFavorite.HasValue)
  917. {
  918. return false;
  919. }
  920. if (request.IsFavoriteOrLiked.HasValue)
  921. {
  922. return false;
  923. }
  924. if (request.IsLiked.HasValue)
  925. {
  926. return false;
  927. }
  928. if (request.IsPlayed.HasValue)
  929. {
  930. return false;
  931. }
  932. if (request.IsResumable.HasValue)
  933. {
  934. return false;
  935. }
  936. if (request.IsFolder.HasValue)
  937. {
  938. return false;
  939. }
  940. if (request.Genres.Count > 0)
  941. {
  942. return false;
  943. }
  944. if (request.GenreIds.Count > 0)
  945. {
  946. return false;
  947. }
  948. if (request.HasImdbId.HasValue)
  949. {
  950. return false;
  951. }
  952. if (request.HasOfficialRating.HasValue)
  953. {
  954. return false;
  955. }
  956. if (request.HasOverview.HasValue)
  957. {
  958. return false;
  959. }
  960. if (request.HasParentalRating.HasValue)
  961. {
  962. return false;
  963. }
  964. if (request.HasSpecialFeature.HasValue)
  965. {
  966. return false;
  967. }
  968. if (request.HasSubtitles.HasValue)
  969. {
  970. return false;
  971. }
  972. if (request.HasThemeSong.HasValue)
  973. {
  974. return false;
  975. }
  976. if (request.HasThemeVideo.HasValue)
  977. {
  978. return false;
  979. }
  980. if (request.HasTmdbId.HasValue)
  981. {
  982. return false;
  983. }
  984. if (request.HasTrailer.HasValue)
  985. {
  986. return false;
  987. }
  988. if (request.ImageTypes.Length > 0)
  989. {
  990. return false;
  991. }
  992. if (request.Is3D.HasValue)
  993. {
  994. return false;
  995. }
  996. if (request.Is4K.HasValue)
  997. {
  998. return false;
  999. }
  1000. if (request.IsHD.HasValue)
  1001. {
  1002. return false;
  1003. }
  1004. if (request.IsLocked.HasValue)
  1005. {
  1006. return false;
  1007. }
  1008. if (request.IsPlaceHolder.HasValue)
  1009. {
  1010. return false;
  1011. }
  1012. if (!string.IsNullOrWhiteSpace(request.Person))
  1013. {
  1014. return false;
  1015. }
  1016. if (request.PersonIds.Length > 0)
  1017. {
  1018. return false;
  1019. }
  1020. if (request.ItemIds.Length > 0)
  1021. {
  1022. return false;
  1023. }
  1024. if (request.StudioIds.Length > 0)
  1025. {
  1026. return false;
  1027. }
  1028. if (request.VideoTypes.Length > 0)
  1029. {
  1030. return false;
  1031. }
  1032. if (request.Years.Length > 0)
  1033. {
  1034. return false;
  1035. }
  1036. if (request.Tags.Length > 0)
  1037. {
  1038. return false;
  1039. }
  1040. if (request.OfficialRatings.Length > 0)
  1041. {
  1042. return false;
  1043. }
  1044. if (request.MinIndexNumber.HasValue)
  1045. {
  1046. return false;
  1047. }
  1048. if (request.OrderBy.Any(o =>
  1049. o.OrderBy == ItemSortBy.CommunityRating ||
  1050. o.OrderBy == ItemSortBy.CriticRating ||
  1051. o.OrderBy == ItemSortBy.Runtime))
  1052. {
  1053. return false;
  1054. }
  1055. return true;
  1056. }
  1057. public virtual IReadOnlyList<BaseItem> GetChildren(User user, bool includeLinkedChildren, out int totalItemCount, InternalItemsQuery query = null)
  1058. {
  1059. ArgumentNullException.ThrowIfNull(user);
  1060. query ??= new InternalItemsQuery();
  1061. query.User = user;
  1062. // the true root should return our users root folder children
  1063. if (IsPhysicalRoot)
  1064. {
  1065. return LibraryManager.GetUserRootFolder().GetChildren(user, includeLinkedChildren, out totalItemCount);
  1066. }
  1067. var result = new Dictionary<Guid, BaseItem>();
  1068. totalItemCount = AddChildren(user, includeLinkedChildren, result, false, query);
  1069. return result.Values.ToArray();
  1070. }
  1071. public virtual IReadOnlyList<BaseItem> GetChildren(User user, bool includeLinkedChildren, InternalItemsQuery query = null)
  1072. {
  1073. return GetChildren(user, includeLinkedChildren, out _, query);
  1074. }
  1075. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  1076. {
  1077. return Children;
  1078. }
  1079. /// <summary>
  1080. /// Adds the children to list.
  1081. /// </summary>
  1082. private int AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, InternalItemsQuery query, HashSet<Folder> visitedFolders = null)
  1083. {
  1084. // Prevent infinite recursion of nested folders
  1085. visitedFolders ??= new HashSet<Folder>();
  1086. if (!visitedFolders.Add(this))
  1087. {
  1088. return 0;
  1089. }
  1090. // If Query.AlbumFolders is set, then enforce the format as per the db in that it permits sub-folders in music albums.
  1091. IEnumerable<BaseItem> children = null;
  1092. if ((query?.DisplayAlbumFolders ?? false) && (this is MusicAlbum))
  1093. {
  1094. children = Children;
  1095. query = null;
  1096. }
  1097. // If there are not sub-folders, proceed as normal.
  1098. if (children is null)
  1099. {
  1100. children = GetEligibleChildrenForRecursiveChildren(user);
  1101. }
  1102. if (includeLinkedChildren)
  1103. {
  1104. children = children.Concat(GetLinkedChildren(user)).ToArray();
  1105. }
  1106. return AddChildrenFromCollection(children, user, includeLinkedChildren, result, recursive, query, visitedFolders);
  1107. }
  1108. private int AddChildrenFromCollection(IEnumerable<BaseItem> children, User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, InternalItemsQuery query, HashSet<Folder> visitedFolders)
  1109. {
  1110. query ??= new InternalItemsQuery();
  1111. var limit = query.Limit;
  1112. query.Limit = 100; // this is a bit of a dirty hack thats in favor of specifically the webUI as it does not show more then +99 elements in its badges so there is no point in reading more then that.
  1113. var visibileChildren = children
  1114. .Where(e => e.IsVisible(user))
  1115. .ToArray();
  1116. var realChildren = visibileChildren
  1117. .Where(e => query is null || UserViewBuilder.FilterItem(e, query))
  1118. .ToArray();
  1119. var childCount = realChildren.Count();
  1120. if (result.Count < query.Limit)
  1121. {
  1122. foreach (var child in realChildren
  1123. .Skip(query.StartIndex ?? 0)
  1124. .TakeWhile(e => query.Limit >= result.Count))
  1125. {
  1126. result[child.Id] = child;
  1127. }
  1128. }
  1129. if (recursive)
  1130. {
  1131. foreach (var child in visibileChildren
  1132. .Where(e => e.IsFolder)
  1133. .OfType<Folder>())
  1134. {
  1135. childCount += child.AddChildren(user, includeLinkedChildren, result, true, query, visitedFolders);
  1136. }
  1137. }
  1138. return childCount;
  1139. }
  1140. public virtual IReadOnlyList<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query, out int totalCount)
  1141. {
  1142. ArgumentNullException.ThrowIfNull(user);
  1143. var result = new Dictionary<Guid, BaseItem>();
  1144. totalCount = AddChildren(user, true, result, true, query);
  1145. return result.Values.ToArray();
  1146. }
  1147. /// <summary>
  1148. /// Gets the recursive children.
  1149. /// </summary>
  1150. /// <returns>IList{BaseItem}.</returns>
  1151. public IReadOnlyList<BaseItem> GetRecursiveChildren()
  1152. {
  1153. return GetRecursiveChildren(true);
  1154. }
  1155. public IReadOnlyList<BaseItem> GetRecursiveChildren(bool includeLinkedChildren)
  1156. {
  1157. return GetRecursiveChildren(i => true, includeLinkedChildren);
  1158. }
  1159. public IReadOnlyList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  1160. {
  1161. return GetRecursiveChildren(filter, true);
  1162. }
  1163. public IReadOnlyList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter, bool includeLinkedChildren)
  1164. {
  1165. var result = new Dictionary<Guid, BaseItem>();
  1166. AddChildrenToList(result, includeLinkedChildren, true, filter);
  1167. return result.Values.ToArray();
  1168. }
  1169. /// <summary>
  1170. /// Adds the children to list.
  1171. /// </summary>
  1172. private void AddChildrenToList(Dictionary<Guid, BaseItem> result, bool includeLinkedChildren, bool recursive, Func<BaseItem, bool> filter)
  1173. {
  1174. foreach (var child in Children)
  1175. {
  1176. if (filter is null || filter(child))
  1177. {
  1178. result[child.Id] = child;
  1179. }
  1180. if (recursive && child.IsFolder)
  1181. {
  1182. var folder = (Folder)child;
  1183. // We can only support includeLinkedChildren for the first folder, or we might end up stuck in a loop of linked items
  1184. folder.AddChildrenToList(result, false, true, filter);
  1185. }
  1186. }
  1187. if (includeLinkedChildren)
  1188. {
  1189. foreach (var child in GetLinkedChildren())
  1190. {
  1191. if (filter is null || filter(child))
  1192. {
  1193. result[child.Id] = child;
  1194. }
  1195. }
  1196. }
  1197. }
  1198. /// <summary>
  1199. /// Gets the linked children.
  1200. /// </summary>
  1201. /// <returns>IEnumerable{BaseItem}.</returns>
  1202. public List<BaseItem> GetLinkedChildren()
  1203. {
  1204. var linkedChildren = LinkedChildren;
  1205. var list = new List<BaseItem>(linkedChildren.Length);
  1206. foreach (var i in linkedChildren)
  1207. {
  1208. var child = GetLinkedChild(i);
  1209. if (child is not null)
  1210. {
  1211. list.Add(child);
  1212. }
  1213. }
  1214. return list;
  1215. }
  1216. public bool ContainsLinkedChildByItemId(Guid itemId)
  1217. {
  1218. var linkedChildren = LinkedChildren;
  1219. foreach (var i in linkedChildren)
  1220. {
  1221. if (i.ItemId.HasValue)
  1222. {
  1223. if (i.ItemId.Value.Equals(itemId))
  1224. {
  1225. return true;
  1226. }
  1227. continue;
  1228. }
  1229. var child = GetLinkedChild(i);
  1230. if (child is not null && child.Id.Equals(itemId))
  1231. {
  1232. return true;
  1233. }
  1234. }
  1235. return false;
  1236. }
  1237. public List<BaseItem> GetLinkedChildren(User user)
  1238. {
  1239. if (!FilterLinkedChildrenPerUser || user is null)
  1240. {
  1241. return GetLinkedChildren();
  1242. }
  1243. var linkedChildren = LinkedChildren;
  1244. var list = new List<BaseItem>(linkedChildren.Length);
  1245. if (linkedChildren.Length == 0)
  1246. {
  1247. return list;
  1248. }
  1249. var allUserRootChildren = LibraryManager.GetUserRootFolder()
  1250. .GetChildren(user, true)
  1251. .OfType<Folder>()
  1252. .ToList();
  1253. var collectionFolderIds = allUserRootChildren
  1254. .Select(i => i.Id)
  1255. .ToList();
  1256. foreach (var i in linkedChildren)
  1257. {
  1258. var child = GetLinkedChild(i);
  1259. if (child is null)
  1260. {
  1261. continue;
  1262. }
  1263. var childOwner = child.GetOwner() ?? child;
  1264. if (child is not IItemByName)
  1265. {
  1266. var childProtocol = childOwner.PathProtocol;
  1267. if (!childProtocol.HasValue || childProtocol.Value != Model.MediaInfo.MediaProtocol.File)
  1268. {
  1269. if (!childOwner.IsVisibleStandalone(user))
  1270. {
  1271. continue;
  1272. }
  1273. }
  1274. else
  1275. {
  1276. var itemCollectionFolderIds =
  1277. LibraryManager.GetCollectionFolders(childOwner, allUserRootChildren).Select(f => f.Id);
  1278. if (!itemCollectionFolderIds.Any(collectionFolderIds.Contains))
  1279. {
  1280. continue;
  1281. }
  1282. }
  1283. }
  1284. list.Add(child);
  1285. }
  1286. return list;
  1287. }
  1288. /// <summary>
  1289. /// Gets the linked children.
  1290. /// </summary>
  1291. /// <returns>IEnumerable{BaseItem}.</returns>
  1292. public IReadOnlyList<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  1293. {
  1294. return LinkedChildren
  1295. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  1296. .Where(i => i.Item2 is not null)
  1297. .ToArray();
  1298. }
  1299. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, IReadOnlyList<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1300. {
  1301. var changesFound = false;
  1302. if (IsFileProtocol)
  1303. {
  1304. if (RefreshLinkedChildren(fileSystemChildren))
  1305. {
  1306. changesFound = true;
  1307. }
  1308. }
  1309. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1310. return baseHasChanges || changesFound;
  1311. }
  1312. /// <summary>
  1313. /// Refreshes the linked children.
  1314. /// </summary>
  1315. /// <param name="fileSystemChildren">The enumerable of file system metadata.</param>
  1316. /// <returns><c>true</c> if the linked children were updated, <c>false</c> otherwise.</returns>
  1317. protected virtual bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  1318. {
  1319. if (SupportsShortcutChildren)
  1320. {
  1321. var newShortcutLinks = fileSystemChildren
  1322. .Where(i => !i.IsDirectory && FileSystem.IsShortcut(i.FullName))
  1323. .Select(i =>
  1324. {
  1325. try
  1326. {
  1327. Logger.LogDebug("Found shortcut at {0}", i.FullName);
  1328. var resolvedPath = CollectionFolder.ApplicationHost.ExpandVirtualPath(FileSystem.ResolveShortcut(i.FullName));
  1329. if (!string.IsNullOrEmpty(resolvedPath))
  1330. {
  1331. return new LinkedChild
  1332. {
  1333. Path = resolvedPath,
  1334. Type = LinkedChildType.Shortcut
  1335. };
  1336. }
  1337. Logger.LogError("Error resolving shortcut {0}", i.FullName);
  1338. return null;
  1339. }
  1340. catch (IOException ex)
  1341. {
  1342. Logger.LogError(ex, "Error resolving shortcut {0}", i.FullName);
  1343. return null;
  1344. }
  1345. })
  1346. .Where(i => i is not null)
  1347. .ToList();
  1348. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1349. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer(FileSystem)))
  1350. {
  1351. Logger.LogInformation("Shortcut links have changed for {0}", Path);
  1352. newShortcutLinks.AddRange(LinkedChildren.Where(i => i.Type == LinkedChildType.Manual));
  1353. LinkedChildren = newShortcutLinks.ToArray();
  1354. return true;
  1355. }
  1356. }
  1357. foreach (var child in LinkedChildren)
  1358. {
  1359. // Reset the cached value
  1360. child.ItemId = null;
  1361. }
  1362. return false;
  1363. }
  1364. /// <summary>
  1365. /// Marks the played.
  1366. /// </summary>
  1367. /// <param name="user">The user.</param>
  1368. /// <param name="datePlayed">The date played.</param>
  1369. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1370. public override void MarkPlayed(
  1371. User user,
  1372. DateTime? datePlayed,
  1373. bool resetPosition)
  1374. {
  1375. var query = new InternalItemsQuery
  1376. {
  1377. User = user,
  1378. Recursive = true,
  1379. IsFolder = false,
  1380. EnableTotalRecordCount = false
  1381. };
  1382. if (!user.DisplayMissingEpisodes)
  1383. {
  1384. query.IsVirtualItem = false;
  1385. }
  1386. var itemsResult = GetItemList(query);
  1387. // Sweep through recursively and update status
  1388. foreach (var item in itemsResult)
  1389. {
  1390. if (item.IsVirtualItem)
  1391. {
  1392. // The querying doesn't support virtual unaired
  1393. var episode = item as Episode;
  1394. if (episode is not null && episode.IsUnaired)
  1395. {
  1396. continue;
  1397. }
  1398. }
  1399. item.MarkPlayed(user, datePlayed, resetPosition);
  1400. }
  1401. }
  1402. /// <summary>
  1403. /// Marks the unplayed.
  1404. /// </summary>
  1405. /// <param name="user">The user.</param>
  1406. public override void MarkUnplayed(User user)
  1407. {
  1408. var itemsResult = GetItemList(new InternalItemsQuery
  1409. {
  1410. User = user,
  1411. Recursive = true,
  1412. IsFolder = false,
  1413. EnableTotalRecordCount = false
  1414. });
  1415. // Sweep through recursively and update status
  1416. foreach (var item in itemsResult)
  1417. {
  1418. item.MarkUnplayed(user);
  1419. }
  1420. }
  1421. public override bool IsPlayed(User user, UserItemData userItemData)
  1422. {
  1423. return ItemRepository.GetIsPlayed(user, Id, true);
  1424. }
  1425. public override bool IsUnplayed(User user, UserItemData userItemData)
  1426. {
  1427. return !IsPlayed(user, userItemData);
  1428. }
  1429. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields)
  1430. {
  1431. if (!SupportsUserDataFromChildren)
  1432. {
  1433. return;
  1434. }
  1435. if (itemDto is not null && fields.ContainsField(ItemFields.RecursiveItemCount))
  1436. {
  1437. itemDto.RecursiveItemCount = GetRecursiveChildCount(user);
  1438. }
  1439. if (SupportsPlayedStatus)
  1440. {
  1441. var unplayedQueryResult = GetItems(new InternalItemsQuery(user)
  1442. {
  1443. Recursive = true,
  1444. IsFolder = false,
  1445. IsVirtualItem = false,
  1446. EnableTotalRecordCount = true,
  1447. Limit = 0,
  1448. IsPlayed = false,
  1449. DtoOptions = new DtoOptions(false)
  1450. {
  1451. EnableImages = false
  1452. }
  1453. }).TotalRecordCount;
  1454. dto.UnplayedItemCount = unplayedQueryResult;
  1455. if (itemDto?.RecursiveItemCount > 0)
  1456. {
  1457. var unplayedPercentage = ((double)unplayedQueryResult / itemDto.RecursiveItemCount.Value) * 100;
  1458. dto.PlayedPercentage = 100 - unplayedPercentage;
  1459. dto.Played = dto.PlayedPercentage.Value >= 100;
  1460. }
  1461. else
  1462. {
  1463. dto.Played = (dto.UnplayedItemCount ?? 0) == 0;
  1464. }
  1465. }
  1466. }
  1467. /// <summary>
  1468. /// Contains constants used when reporting scan progress.
  1469. /// </summary>
  1470. private static class ProgressHelpers
  1471. {
  1472. /// <summary>
  1473. /// Reported after the folders immediate children are retrieved.
  1474. /// </summary>
  1475. public const int RetrievedChildren = 5;
  1476. /// <summary>
  1477. /// Reported after add, updating, or deleting child items from the LibraryManager.
  1478. /// </summary>
  1479. public const int UpdatedChildItems = 10;
  1480. /// <summary>
  1481. /// Reported once subfolders are scanned.
  1482. /// When scanning subfolders, the progress will be between [UpdatedItems, ScannedSubfolders].
  1483. /// </summary>
  1484. public const int ScannedSubfolders = 50;
  1485. /// <summary>
  1486. /// Reported once metadata is refreshed.
  1487. /// When refreshing metadata, the progress will be between [ScannedSubfolders, MetadataRefreshed].
  1488. /// </summary>
  1489. public const int RefreshedMetadata = 100;
  1490. /// <summary>
  1491. /// Gets the current progress given the previous step, next step, and progress in between.
  1492. /// </summary>
  1493. /// <param name="previousProgressStep">The previous progress step.</param>
  1494. /// <param name="nextProgressStep">The next progress step.</param>
  1495. /// <param name="currentProgress">The current progress step.</param>
  1496. /// <returns>The progress.</returns>
  1497. public static double GetProgress(int previousProgressStep, int nextProgressStep, double currentProgress)
  1498. {
  1499. return previousProgressStep + ((nextProgressStep - previousProgressStep) * (currentProgress / 100));
  1500. }
  1501. }
  1502. }
  1503. }