Folder.cs 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824
  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. items = GetRecursiveChildren(user, query, out totalCount);
  608. query.Limit = null;
  609. query.StartIndex = null; // override these here as they have already been applied
  610. }
  611. var result = PostFilterAndSort(items, query);
  612. result.TotalRecordCount = totalCount;
  613. return result;
  614. }
  615. if (this is not UserRootFolder
  616. && this is not AggregateFolder
  617. && query.ParentId.IsEmpty())
  618. {
  619. query.Parent = this;
  620. }
  621. if (RequiresPostFiltering2(query))
  622. {
  623. return QueryWithPostFiltering2(query);
  624. }
  625. return LibraryManager.GetItemsResult(query);
  626. }
  627. protected QueryResult<BaseItem> QueryWithPostFiltering2(InternalItemsQuery query)
  628. {
  629. var startIndex = query.StartIndex;
  630. var limit = query.Limit;
  631. query.StartIndex = null;
  632. query.Limit = null;
  633. IEnumerable<BaseItem> itemsList = LibraryManager.GetItemList(query);
  634. var user = query.User;
  635. if (user is not null)
  636. {
  637. // needed for boxsets
  638. itemsList = itemsList.Where(i => i.IsVisibleStandalone(query.User));
  639. }
  640. IEnumerable<BaseItem> returnItems;
  641. int totalCount = 0;
  642. if (query.EnableTotalRecordCount)
  643. {
  644. var itemArray = itemsList.ToArray();
  645. totalCount = itemArray.Length;
  646. returnItems = itemArray;
  647. }
  648. else
  649. {
  650. returnItems = itemsList;
  651. }
  652. if (limit.HasValue)
  653. {
  654. returnItems = returnItems.Skip(startIndex ?? 0).Take(limit.Value);
  655. }
  656. else if (startIndex.HasValue)
  657. {
  658. returnItems = returnItems.Skip(startIndex.Value);
  659. }
  660. return new QueryResult<BaseItem>(
  661. query.StartIndex,
  662. totalCount,
  663. returnItems.ToArray());
  664. }
  665. private bool RequiresPostFiltering2(InternalItemsQuery query)
  666. {
  667. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes[0] == BaseItemKind.BoxSet)
  668. {
  669. Logger.LogDebug("Query requires post-filtering due to BoxSet query");
  670. return true;
  671. }
  672. return false;
  673. }
  674. private bool RequiresPostFiltering(InternalItemsQuery query)
  675. {
  676. if (LinkedChildren.Length > 0)
  677. {
  678. if (this is not ICollectionFolder)
  679. {
  680. Logger.LogDebug("{Type}: Query requires post-filtering due to LinkedChildren.", GetType().Name);
  681. return true;
  682. }
  683. }
  684. // Filter by Video3DFormat
  685. if (query.Is3D.HasValue)
  686. {
  687. Logger.LogDebug("Query requires post-filtering due to Is3D");
  688. return true;
  689. }
  690. if (query.HasOfficialRating.HasValue)
  691. {
  692. Logger.LogDebug("Query requires post-filtering due to HasOfficialRating");
  693. return true;
  694. }
  695. if (query.IsPlaceHolder.HasValue)
  696. {
  697. Logger.LogDebug("Query requires post-filtering due to IsPlaceHolder");
  698. return true;
  699. }
  700. if (query.HasSpecialFeature.HasValue)
  701. {
  702. Logger.LogDebug("Query requires post-filtering due to HasSpecialFeature");
  703. return true;
  704. }
  705. if (query.HasSubtitles.HasValue)
  706. {
  707. Logger.LogDebug("Query requires post-filtering due to HasSubtitles");
  708. return true;
  709. }
  710. if (query.HasTrailer.HasValue)
  711. {
  712. Logger.LogDebug("Query requires post-filtering due to HasTrailer");
  713. return true;
  714. }
  715. if (query.HasThemeSong.HasValue)
  716. {
  717. Logger.LogDebug("Query requires post-filtering due to HasThemeSong");
  718. return true;
  719. }
  720. if (query.HasThemeVideo.HasValue)
  721. {
  722. Logger.LogDebug("Query requires post-filtering due to HasThemeVideo");
  723. return true;
  724. }
  725. // Filter by VideoType
  726. if (query.VideoTypes.Length > 0)
  727. {
  728. Logger.LogDebug("Query requires post-filtering due to VideoTypes");
  729. return true;
  730. }
  731. if (CollapseBoxSetItems(query, this, query.User, ConfigurationManager))
  732. {
  733. Logger.LogDebug("Query requires post-filtering due to CollapseBoxSetItems");
  734. return true;
  735. }
  736. if (!query.AdjacentTo.IsNullOrEmpty())
  737. {
  738. Logger.LogDebug("Query requires post-filtering due to AdjacentTo");
  739. return true;
  740. }
  741. if (query.SeriesStatuses.Length > 0)
  742. {
  743. Logger.LogDebug("Query requires post-filtering due to SeriesStatuses");
  744. return true;
  745. }
  746. if (query.AiredDuringSeason.HasValue)
  747. {
  748. Logger.LogDebug("Query requires post-filtering due to AiredDuringSeason");
  749. return true;
  750. }
  751. if (query.IsPlayed.HasValue)
  752. {
  753. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(BaseItemKind.Series))
  754. {
  755. Logger.LogDebug("Query requires post-filtering due to IsPlayed");
  756. return true;
  757. }
  758. }
  759. return false;
  760. }
  761. private static BaseItem[] SortItemsByRequest(InternalItemsQuery query, IReadOnlyList<BaseItem> items)
  762. {
  763. return items.OrderBy(i => Array.IndexOf(query.ItemIds, i.Id)).ToArray();
  764. }
  765. public QueryResult<BaseItem> GetItems(InternalItemsQuery query)
  766. {
  767. if (query.ItemIds.Length > 0)
  768. {
  769. var result = LibraryManager.GetItemsResult(query);
  770. if (query.OrderBy.Count == 0 && query.ItemIds.Length > 1)
  771. {
  772. result.Items = SortItemsByRequest(query, result.Items);
  773. }
  774. return result;
  775. }
  776. return GetItemsInternal(query);
  777. }
  778. public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query)
  779. {
  780. query.EnableTotalRecordCount = false;
  781. if (query.ItemIds.Length > 0)
  782. {
  783. var result = LibraryManager.GetItemList(query);
  784. if (query.OrderBy.Count == 0 && query.ItemIds.Length > 1)
  785. {
  786. return SortItemsByRequest(query, result);
  787. }
  788. return result;
  789. }
  790. return GetItemsInternal(query).Items;
  791. }
  792. protected virtual QueryResult<BaseItem> GetItemsInternal(InternalItemsQuery query)
  793. {
  794. if (SourceType == SourceType.Channel)
  795. {
  796. try
  797. {
  798. query.Parent = this;
  799. query.ChannelIds = new[] { ChannelId };
  800. // Don't blow up here because it could cause parent screens with other content to fail
  801. return ChannelManager.GetChannelItemsInternal(query, new Progress<double>(), CancellationToken.None).GetAwaiter().GetResult();
  802. }
  803. catch
  804. {
  805. // Already logged at lower levels
  806. return new QueryResult<BaseItem>();
  807. }
  808. }
  809. if (query.Recursive)
  810. {
  811. return QueryRecursive(query);
  812. }
  813. var user = query.User;
  814. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  815. IEnumerable<BaseItem> items;
  816. int totalItemCount = 0;
  817. if (query.User is null)
  818. {
  819. items = Children.Where(filter);
  820. totalItemCount = items.Count();
  821. }
  822. else
  823. {
  824. // need to pass this param to the children.
  825. var childQuery = new InternalItemsQuery
  826. {
  827. DisplayAlbumFolders = query.DisplayAlbumFolders,
  828. Limit = query.Limit,
  829. StartIndex = query.StartIndex,
  830. NameStartsWith = query.NameStartsWith,
  831. NameStartsWithOrGreater = query.NameStartsWithOrGreater,
  832. NameLessThan = query.NameLessThan
  833. };
  834. items = GetChildren(user, true, out totalItemCount, childQuery).Where(filter);
  835. query.Limit = null;
  836. query.StartIndex = null;
  837. }
  838. var result = PostFilterAndSort(items, query);
  839. result.TotalRecordCount = totalItemCount;
  840. return result;
  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. return UserViewBuilder.SortAndPage(items, null, query, LibraryManager);
  870. }
  871. private static IEnumerable<BaseItem> CollapseBoxSetItemsIfNeeded(
  872. IEnumerable<BaseItem> items,
  873. InternalItemsQuery query,
  874. BaseItem queryParent,
  875. User user,
  876. IServerConfigurationManager configurationManager,
  877. ICollectionManager collectionManager)
  878. {
  879. ArgumentNullException.ThrowIfNull(items);
  880. if (CollapseBoxSetItems(query, queryParent, user, configurationManager))
  881. {
  882. items = collectionManager.CollapseItemsWithinBoxSets(items, user);
  883. }
  884. return items;
  885. }
  886. private static bool CollapseBoxSetItems(
  887. InternalItemsQuery query,
  888. BaseItem queryParent,
  889. User user,
  890. IServerConfigurationManager configurationManager)
  891. {
  892. // Could end up stuck in a loop like this
  893. if (queryParent is BoxSet)
  894. {
  895. return false;
  896. }
  897. if (queryParent is Season)
  898. {
  899. return false;
  900. }
  901. if (queryParent is MusicAlbum)
  902. {
  903. return false;
  904. }
  905. if (queryParent is MusicArtist)
  906. {
  907. return false;
  908. }
  909. var param = query.CollapseBoxSetItems;
  910. if (!param.HasValue)
  911. {
  912. if (user is not null && query.IncludeItemTypes.Any(type =>
  913. (type == BaseItemKind.Movie && !configurationManager.Configuration.EnableGroupingMoviesIntoCollections) ||
  914. (type == BaseItemKind.Series && !configurationManager.Configuration.EnableGroupingShowsIntoCollections)))
  915. {
  916. return false;
  917. }
  918. if (query.IncludeItemTypes.Length == 0
  919. || query.IncludeItemTypes.Any(type => type == BaseItemKind.Movie || type == BaseItemKind.Series))
  920. {
  921. param = true;
  922. }
  923. }
  924. return param.HasValue && param.Value && AllowBoxSetCollapsing(query);
  925. }
  926. private static bool AllowBoxSetCollapsing(InternalItemsQuery request)
  927. {
  928. if (request.IsFavorite.HasValue)
  929. {
  930. return false;
  931. }
  932. if (request.IsFavoriteOrLiked.HasValue)
  933. {
  934. return false;
  935. }
  936. if (request.IsLiked.HasValue)
  937. {
  938. return false;
  939. }
  940. if (request.IsPlayed.HasValue)
  941. {
  942. return false;
  943. }
  944. if (request.IsResumable.HasValue)
  945. {
  946. return false;
  947. }
  948. if (request.IsFolder.HasValue)
  949. {
  950. return false;
  951. }
  952. if (request.Genres.Count > 0)
  953. {
  954. return false;
  955. }
  956. if (request.GenreIds.Count > 0)
  957. {
  958. return false;
  959. }
  960. if (request.HasImdbId.HasValue)
  961. {
  962. return false;
  963. }
  964. if (request.HasOfficialRating.HasValue)
  965. {
  966. return false;
  967. }
  968. if (request.HasOverview.HasValue)
  969. {
  970. return false;
  971. }
  972. if (request.HasParentalRating.HasValue)
  973. {
  974. return false;
  975. }
  976. if (request.HasSpecialFeature.HasValue)
  977. {
  978. return false;
  979. }
  980. if (request.HasSubtitles.HasValue)
  981. {
  982. return false;
  983. }
  984. if (request.HasThemeSong.HasValue)
  985. {
  986. return false;
  987. }
  988. if (request.HasThemeVideo.HasValue)
  989. {
  990. return false;
  991. }
  992. if (request.HasTmdbId.HasValue)
  993. {
  994. return false;
  995. }
  996. if (request.HasTrailer.HasValue)
  997. {
  998. return false;
  999. }
  1000. if (request.ImageTypes.Length > 0)
  1001. {
  1002. return false;
  1003. }
  1004. if (request.Is3D.HasValue)
  1005. {
  1006. return false;
  1007. }
  1008. if (request.Is4K.HasValue)
  1009. {
  1010. return false;
  1011. }
  1012. if (request.IsHD.HasValue)
  1013. {
  1014. return false;
  1015. }
  1016. if (request.IsLocked.HasValue)
  1017. {
  1018. return false;
  1019. }
  1020. if (request.IsPlaceHolder.HasValue)
  1021. {
  1022. return false;
  1023. }
  1024. if (!string.IsNullOrWhiteSpace(request.Person))
  1025. {
  1026. return false;
  1027. }
  1028. if (request.PersonIds.Length > 0)
  1029. {
  1030. return false;
  1031. }
  1032. if (request.ItemIds.Length > 0)
  1033. {
  1034. return false;
  1035. }
  1036. if (request.StudioIds.Length > 0)
  1037. {
  1038. return false;
  1039. }
  1040. if (request.VideoTypes.Length > 0)
  1041. {
  1042. return false;
  1043. }
  1044. if (request.Years.Length > 0)
  1045. {
  1046. return false;
  1047. }
  1048. if (request.Tags.Length > 0)
  1049. {
  1050. return false;
  1051. }
  1052. if (request.OfficialRatings.Length > 0)
  1053. {
  1054. return false;
  1055. }
  1056. if (request.MinIndexNumber.HasValue)
  1057. {
  1058. return false;
  1059. }
  1060. if (request.OrderBy.Any(o =>
  1061. o.OrderBy == ItemSortBy.CommunityRating ||
  1062. o.OrderBy == ItemSortBy.CriticRating ||
  1063. o.OrderBy == ItemSortBy.Runtime))
  1064. {
  1065. return false;
  1066. }
  1067. return true;
  1068. }
  1069. public virtual IReadOnlyList<BaseItem> GetChildren(User user, bool includeLinkedChildren, out int totalItemCount, InternalItemsQuery query = null)
  1070. {
  1071. ArgumentNullException.ThrowIfNull(user);
  1072. query ??= new InternalItemsQuery();
  1073. query.User = user;
  1074. // the true root should return our users root folder children
  1075. if (IsPhysicalRoot)
  1076. {
  1077. return LibraryManager.GetUserRootFolder().GetChildren(user, includeLinkedChildren, out totalItemCount);
  1078. }
  1079. var result = new Dictionary<Guid, BaseItem>();
  1080. totalItemCount = AddChildren(user, includeLinkedChildren, result, false, query);
  1081. return result.Values.ToArray();
  1082. }
  1083. public virtual IReadOnlyList<BaseItem> GetChildren(User user, bool includeLinkedChildren, InternalItemsQuery query = null)
  1084. {
  1085. return GetChildren(user, includeLinkedChildren, out _, query);
  1086. }
  1087. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  1088. {
  1089. return Children;
  1090. }
  1091. /// <summary>
  1092. /// Adds the children to list.
  1093. /// </summary>
  1094. private int AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, InternalItemsQuery query, HashSet<Folder> visitedFolders = null)
  1095. {
  1096. // Prevent infinite recursion of nested folders
  1097. visitedFolders ??= new HashSet<Folder>();
  1098. if (!visitedFolders.Add(this))
  1099. {
  1100. return 0;
  1101. }
  1102. // If Query.AlbumFolders is set, then enforce the format as per the db in that it permits sub-folders in music albums.
  1103. IEnumerable<BaseItem> children = null;
  1104. if ((query?.DisplayAlbumFolders ?? false) && (this is MusicAlbum))
  1105. {
  1106. children = Children;
  1107. query = null;
  1108. }
  1109. // If there are not sub-folders, proceed as normal.
  1110. if (children is null)
  1111. {
  1112. children = GetEligibleChildrenForRecursiveChildren(user);
  1113. }
  1114. if (includeLinkedChildren)
  1115. {
  1116. children = children.Concat(GetLinkedChildren(user)).ToArray();
  1117. }
  1118. return AddChildrenFromCollection(children, user, includeLinkedChildren, result, recursive, query, visitedFolders);
  1119. }
  1120. private int AddChildrenFromCollection(IEnumerable<BaseItem> children, User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, InternalItemsQuery query, HashSet<Folder> visitedFolders)
  1121. {
  1122. query ??= new InternalItemsQuery();
  1123. var limit = query.Limit > 0 ? query.Limit : int.MaxValue;
  1124. query.Limit = 0;
  1125. var visibleChildren = children
  1126. .Where(e => e.IsVisible(user))
  1127. .ToArray();
  1128. var realChildren = visibleChildren
  1129. .Where(e => query is null || UserViewBuilder.FilterItem(e, query))
  1130. .ToArray();
  1131. if (this is BoxSet && (query.OrderBy is null || query.OrderBy.Count == 0))
  1132. {
  1133. realChildren = realChildren
  1134. .OrderBy(e => e.ProductionYear ?? int.MaxValue)
  1135. .ToArray();
  1136. }
  1137. var childCount = realChildren.Length;
  1138. if (result.Count < limit)
  1139. {
  1140. var remainingCount = (int)(limit - result.Count);
  1141. foreach (var child in realChildren
  1142. .Skip(query.StartIndex ?? 0)
  1143. .Take(remainingCount))
  1144. {
  1145. result[child.Id] = child;
  1146. }
  1147. }
  1148. if (recursive)
  1149. {
  1150. foreach (var child in visibleChildren
  1151. .Where(e => e.IsFolder)
  1152. .OfType<Folder>())
  1153. {
  1154. childCount += child.AddChildren(user, includeLinkedChildren, result, true, query, visitedFolders);
  1155. }
  1156. }
  1157. return childCount;
  1158. }
  1159. public virtual IReadOnlyList<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query, out int totalCount)
  1160. {
  1161. ArgumentNullException.ThrowIfNull(user);
  1162. var result = new Dictionary<Guid, BaseItem>();
  1163. totalCount = AddChildren(user, true, result, true, query);
  1164. return result.Values.ToArray();
  1165. }
  1166. /// <summary>
  1167. /// Gets the recursive children.
  1168. /// </summary>
  1169. /// <returns>IList{BaseItem}.</returns>
  1170. public IReadOnlyList<BaseItem> GetRecursiveChildren()
  1171. {
  1172. return GetRecursiveChildren(true);
  1173. }
  1174. public IReadOnlyList<BaseItem> GetRecursiveChildren(bool includeLinkedChildren)
  1175. {
  1176. return GetRecursiveChildren(i => true, includeLinkedChildren);
  1177. }
  1178. public IReadOnlyList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  1179. {
  1180. return GetRecursiveChildren(filter, true);
  1181. }
  1182. public IReadOnlyList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter, bool includeLinkedChildren)
  1183. {
  1184. var result = new Dictionary<Guid, BaseItem>();
  1185. AddChildrenToList(result, includeLinkedChildren, true, filter);
  1186. return result.Values.ToArray();
  1187. }
  1188. /// <summary>
  1189. /// Adds the children to list.
  1190. /// </summary>
  1191. private void AddChildrenToList(Dictionary<Guid, BaseItem> result, bool includeLinkedChildren, bool recursive, Func<BaseItem, bool> filter)
  1192. {
  1193. foreach (var child in Children)
  1194. {
  1195. if (filter is null || filter(child))
  1196. {
  1197. result[child.Id] = child;
  1198. }
  1199. if (recursive && child.IsFolder)
  1200. {
  1201. var folder = (Folder)child;
  1202. // We can only support includeLinkedChildren for the first folder, or we might end up stuck in a loop of linked items
  1203. folder.AddChildrenToList(result, false, true, filter);
  1204. }
  1205. }
  1206. if (includeLinkedChildren)
  1207. {
  1208. foreach (var child in GetLinkedChildren())
  1209. {
  1210. if (filter is null || filter(child))
  1211. {
  1212. result[child.Id] = child;
  1213. }
  1214. }
  1215. }
  1216. }
  1217. /// <summary>
  1218. /// Gets the linked children.
  1219. /// </summary>
  1220. /// <returns>IEnumerable{BaseItem}.</returns>
  1221. public List<BaseItem> GetLinkedChildren()
  1222. {
  1223. var linkedChildren = LinkedChildren;
  1224. var list = new List<BaseItem>(linkedChildren.Length);
  1225. foreach (var i in linkedChildren)
  1226. {
  1227. var child = GetLinkedChild(i);
  1228. if (child is not null)
  1229. {
  1230. list.Add(child);
  1231. }
  1232. }
  1233. return list;
  1234. }
  1235. public bool ContainsLinkedChildByItemId(Guid itemId)
  1236. {
  1237. var linkedChildren = LinkedChildren;
  1238. foreach (var i in linkedChildren)
  1239. {
  1240. if (i.ItemId.HasValue)
  1241. {
  1242. if (i.ItemId.Value.Equals(itemId))
  1243. {
  1244. return true;
  1245. }
  1246. continue;
  1247. }
  1248. var child = GetLinkedChild(i);
  1249. if (child is not null && child.Id.Equals(itemId))
  1250. {
  1251. return true;
  1252. }
  1253. }
  1254. return false;
  1255. }
  1256. public List<BaseItem> GetLinkedChildren(User user)
  1257. {
  1258. if (!FilterLinkedChildrenPerUser || user is null)
  1259. {
  1260. return GetLinkedChildren();
  1261. }
  1262. var linkedChildren = LinkedChildren;
  1263. var list = new List<BaseItem>(linkedChildren.Length);
  1264. if (linkedChildren.Length == 0)
  1265. {
  1266. return list;
  1267. }
  1268. var allUserRootChildren = LibraryManager.GetUserRootFolder()
  1269. .GetChildren(user, true)
  1270. .OfType<Folder>()
  1271. .ToList();
  1272. var collectionFolderIds = allUserRootChildren
  1273. .Select(i => i.Id)
  1274. .ToList();
  1275. foreach (var i in linkedChildren)
  1276. {
  1277. var child = GetLinkedChild(i);
  1278. if (child is null)
  1279. {
  1280. continue;
  1281. }
  1282. var childOwner = child.GetOwner() ?? child;
  1283. if (child is not IItemByName)
  1284. {
  1285. var childProtocol = childOwner.PathProtocol;
  1286. if (!childProtocol.HasValue || childProtocol.Value != Model.MediaInfo.MediaProtocol.File)
  1287. {
  1288. if (!childOwner.IsVisibleStandalone(user))
  1289. {
  1290. continue;
  1291. }
  1292. }
  1293. else
  1294. {
  1295. var itemCollectionFolderIds =
  1296. LibraryManager.GetCollectionFolders(childOwner, allUserRootChildren).Select(f => f.Id);
  1297. if (!itemCollectionFolderIds.Any(collectionFolderIds.Contains))
  1298. {
  1299. continue;
  1300. }
  1301. }
  1302. }
  1303. list.Add(child);
  1304. }
  1305. return list;
  1306. }
  1307. /// <summary>
  1308. /// Gets the linked children.
  1309. /// </summary>
  1310. /// <returns>IEnumerable{BaseItem}.</returns>
  1311. public IReadOnlyList<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  1312. {
  1313. return LinkedChildren
  1314. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  1315. .Where(i => i.Item2 is not null)
  1316. .ToArray();
  1317. }
  1318. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, IReadOnlyList<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1319. {
  1320. var changesFound = false;
  1321. if (IsFileProtocol)
  1322. {
  1323. if (RefreshLinkedChildren(fileSystemChildren))
  1324. {
  1325. changesFound = true;
  1326. }
  1327. }
  1328. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1329. return baseHasChanges || changesFound;
  1330. }
  1331. /// <summary>
  1332. /// Refreshes the linked children.
  1333. /// </summary>
  1334. /// <param name="fileSystemChildren">The enumerable of file system metadata.</param>
  1335. /// <returns><c>true</c> if the linked children were updated, <c>false</c> otherwise.</returns>
  1336. protected virtual bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  1337. {
  1338. if (SupportsShortcutChildren)
  1339. {
  1340. var newShortcutLinks = fileSystemChildren
  1341. .Where(i => !i.IsDirectory && FileSystem.IsShortcut(i.FullName))
  1342. .Select(i =>
  1343. {
  1344. try
  1345. {
  1346. Logger.LogDebug("Found shortcut at {0}", i.FullName);
  1347. var resolvedPath = CollectionFolder.ApplicationHost.ExpandVirtualPath(FileSystem.ResolveShortcut(i.FullName));
  1348. if (!string.IsNullOrEmpty(resolvedPath))
  1349. {
  1350. return new LinkedChild
  1351. {
  1352. Path = resolvedPath,
  1353. Type = LinkedChildType.Shortcut
  1354. };
  1355. }
  1356. Logger.LogError("Error resolving shortcut {0}", i.FullName);
  1357. return null;
  1358. }
  1359. catch (IOException ex)
  1360. {
  1361. Logger.LogError(ex, "Error resolving shortcut {0}", i.FullName);
  1362. return null;
  1363. }
  1364. })
  1365. .Where(i => i is not null)
  1366. .ToList();
  1367. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1368. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer(FileSystem)))
  1369. {
  1370. Logger.LogInformation("Shortcut links have changed for {0}", Path);
  1371. newShortcutLinks.AddRange(LinkedChildren.Where(i => i.Type == LinkedChildType.Manual));
  1372. LinkedChildren = newShortcutLinks.ToArray();
  1373. return true;
  1374. }
  1375. }
  1376. foreach (var child in LinkedChildren)
  1377. {
  1378. // Reset the cached value
  1379. child.ItemId = null;
  1380. }
  1381. return false;
  1382. }
  1383. /// <summary>
  1384. /// Marks the played.
  1385. /// </summary>
  1386. /// <param name="user">The user.</param>
  1387. /// <param name="datePlayed">The date played.</param>
  1388. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1389. public override void MarkPlayed(
  1390. User user,
  1391. DateTime? datePlayed,
  1392. bool resetPosition)
  1393. {
  1394. var query = new InternalItemsQuery
  1395. {
  1396. User = user,
  1397. Recursive = true,
  1398. IsFolder = false,
  1399. EnableTotalRecordCount = false
  1400. };
  1401. if (!user.DisplayMissingEpisodes)
  1402. {
  1403. query.IsVirtualItem = false;
  1404. }
  1405. var itemsResult = GetItemList(query);
  1406. // Sweep through recursively and update status
  1407. foreach (var item in itemsResult)
  1408. {
  1409. if (item.IsVirtualItem)
  1410. {
  1411. // The querying doesn't support virtual unaired
  1412. var episode = item as Episode;
  1413. if (episode is not null && episode.IsUnaired)
  1414. {
  1415. continue;
  1416. }
  1417. }
  1418. item.MarkPlayed(user, datePlayed, resetPosition);
  1419. }
  1420. }
  1421. /// <summary>
  1422. /// Marks the unplayed.
  1423. /// </summary>
  1424. /// <param name="user">The user.</param>
  1425. public override void MarkUnplayed(User user)
  1426. {
  1427. var itemsResult = GetItemList(new InternalItemsQuery
  1428. {
  1429. User = user,
  1430. Recursive = true,
  1431. IsFolder = false,
  1432. EnableTotalRecordCount = false
  1433. });
  1434. // Sweep through recursively and update status
  1435. foreach (var item in itemsResult)
  1436. {
  1437. item.MarkUnplayed(user);
  1438. }
  1439. }
  1440. public override bool IsPlayed(User user, UserItemData userItemData)
  1441. {
  1442. return ItemRepository.GetIsPlayed(user, Id, true);
  1443. }
  1444. public override bool IsUnplayed(User user, UserItemData userItemData)
  1445. {
  1446. return !IsPlayed(user, userItemData);
  1447. }
  1448. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields)
  1449. {
  1450. if (!SupportsUserDataFromChildren)
  1451. {
  1452. return;
  1453. }
  1454. if (itemDto is not null && fields.ContainsField(ItemFields.RecursiveItemCount))
  1455. {
  1456. itemDto.RecursiveItemCount = GetRecursiveChildCount(user);
  1457. }
  1458. if (SupportsPlayedStatus)
  1459. {
  1460. var unplayedQueryResult = GetItems(new InternalItemsQuery(user)
  1461. {
  1462. Recursive = true,
  1463. IsFolder = false,
  1464. IsVirtualItem = false,
  1465. EnableTotalRecordCount = true,
  1466. Limit = 0,
  1467. IsPlayed = false,
  1468. DtoOptions = new DtoOptions(false)
  1469. {
  1470. EnableImages = false
  1471. }
  1472. }).TotalRecordCount;
  1473. dto.UnplayedItemCount = unplayedQueryResult;
  1474. if (itemDto?.RecursiveItemCount > 0)
  1475. {
  1476. var unplayedPercentage = ((double)unplayedQueryResult / itemDto.RecursiveItemCount.Value) * 100;
  1477. dto.PlayedPercentage = 100 - unplayedPercentage;
  1478. dto.Played = dto.PlayedPercentage.Value >= 100;
  1479. }
  1480. else
  1481. {
  1482. dto.Played = (dto.UnplayedItemCount ?? 0) == 0;
  1483. }
  1484. }
  1485. }
  1486. /// <summary>
  1487. /// Contains constants used when reporting scan progress.
  1488. /// </summary>
  1489. private static class ProgressHelpers
  1490. {
  1491. /// <summary>
  1492. /// Reported after the folders immediate children are retrieved.
  1493. /// </summary>
  1494. public const int RetrievedChildren = 5;
  1495. /// <summary>
  1496. /// Reported after add, updating, or deleting child items from the LibraryManager.
  1497. /// </summary>
  1498. public const int UpdatedChildItems = 10;
  1499. /// <summary>
  1500. /// Reported once subfolders are scanned.
  1501. /// When scanning subfolders, the progress will be between [UpdatedItems, ScannedSubfolders].
  1502. /// </summary>
  1503. public const int ScannedSubfolders = 50;
  1504. /// <summary>
  1505. /// Reported once metadata is refreshed.
  1506. /// When refreshing metadata, the progress will be between [ScannedSubfolders, MetadataRefreshed].
  1507. /// </summary>
  1508. public const int RefreshedMetadata = 100;
  1509. /// <summary>
  1510. /// Gets the current progress given the previous step, next step, and progress in between.
  1511. /// </summary>
  1512. /// <param name="previousProgressStep">The previous progress step.</param>
  1513. /// <param name="nextProgressStep">The next progress step.</param>
  1514. /// <param name="currentProgress">The current progress step.</param>
  1515. /// <returns>The progress.</returns>
  1516. public static double GetProgress(int previousProgressStep, int nextProgressStep, double currentProgress)
  1517. {
  1518. return previousProgressStep + ((nextProgressStep - previousProgressStep) * (currentProgress / 100));
  1519. }
  1520. }
  1521. }
  1522. }