Folder.cs 63 KB

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