Folder.cs 61 KB

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