Folder.cs 61 KB

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