Folder.cs 60 KB

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