Folder.cs 63 KB

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