Folder.cs 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814
  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.CreateItems(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.GenreIds.Count > 0)
  1033. {
  1034. return false;
  1035. }
  1036. if (request.VideoTypes.Length > 0)
  1037. {
  1038. return false;
  1039. }
  1040. if (request.Years.Length > 0)
  1041. {
  1042. return false;
  1043. }
  1044. if (request.Tags.Length > 0)
  1045. {
  1046. return false;
  1047. }
  1048. if (request.OfficialRatings.Length > 0)
  1049. {
  1050. return false;
  1051. }
  1052. if (request.MinCommunityRating.HasValue)
  1053. {
  1054. return false;
  1055. }
  1056. if (request.MinCriticRating.HasValue)
  1057. {
  1058. return false;
  1059. }
  1060. if (request.MinIndexNumber.HasValue)
  1061. {
  1062. return false;
  1063. }
  1064. return true;
  1065. }
  1066. public IReadOnlyList<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  1067. {
  1068. ArgumentNullException.ThrowIfNull(user);
  1069. return GetChildren(user, includeLinkedChildren, new InternalItemsQuery(user));
  1070. }
  1071. public virtual IReadOnlyList<BaseItem> GetChildren(User user, bool includeLinkedChildren, InternalItemsQuery query)
  1072. {
  1073. ArgumentNullException.ThrowIfNull(user);
  1074. // the true root should return our users root folder children
  1075. if (IsPhysicalRoot)
  1076. {
  1077. return LibraryManager.GetUserRootFolder().GetChildren(user, includeLinkedChildren);
  1078. }
  1079. var result = new Dictionary<Guid, BaseItem>();
  1080. AddChildren(user, includeLinkedChildren, result, false, query);
  1081. return result.Values.ToImmutableList();
  1082. }
  1083. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  1084. {
  1085. return Children;
  1086. }
  1087. /// <summary>
  1088. /// Adds the children to list.
  1089. /// </summary>
  1090. private void AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, InternalItemsQuery query, HashSet<Folder> visitedFolders = null)
  1091. {
  1092. // Prevent infinite recursion of nested folders
  1093. visitedFolders ??= new HashSet<Folder>();
  1094. if (!visitedFolders.Add(this))
  1095. {
  1096. return;
  1097. }
  1098. // If Query.AlbumFolders is set, then enforce the format as per the db in that it permits sub-folders in music albums.
  1099. IEnumerable<BaseItem> children = null;
  1100. if ((query?.DisplayAlbumFolders ?? false) && (this is MusicAlbum))
  1101. {
  1102. children = Children;
  1103. query = null;
  1104. }
  1105. // If there are not sub-folders, proceed as normal.
  1106. if (children is null)
  1107. {
  1108. children = GetEligibleChildrenForRecursiveChildren(user);
  1109. }
  1110. AddChildrenFromCollection(children, user, includeLinkedChildren, result, recursive, query, visitedFolders);
  1111. if (includeLinkedChildren)
  1112. {
  1113. AddChildrenFromCollection(GetLinkedChildren(user), user, includeLinkedChildren, result, recursive, query, visitedFolders);
  1114. }
  1115. }
  1116. private void AddChildrenFromCollection(IEnumerable<BaseItem> children, User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, InternalItemsQuery query, HashSet<Folder> visitedFolders)
  1117. {
  1118. foreach (var child in children)
  1119. {
  1120. if (!child.IsVisible(user))
  1121. {
  1122. continue;
  1123. }
  1124. if (query is null || UserViewBuilder.FilterItem(child, query))
  1125. {
  1126. result[child.Id] = child;
  1127. }
  1128. if (recursive && child.IsFolder)
  1129. {
  1130. var folder = (Folder)child;
  1131. folder.AddChildren(user, includeLinkedChildren, result, true, query, visitedFolders);
  1132. }
  1133. }
  1134. }
  1135. public virtual IReadOnlyList<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query)
  1136. {
  1137. ArgumentNullException.ThrowIfNull(user);
  1138. var result = new Dictionary<Guid, BaseItem>();
  1139. AddChildren(user, true, result, true, query);
  1140. return result.Values.ToImmutableList();
  1141. }
  1142. /// <summary>
  1143. /// Gets the recursive children.
  1144. /// </summary>
  1145. /// <returns>IList{BaseItem}.</returns>
  1146. public IReadOnlyList<BaseItem> GetRecursiveChildren()
  1147. {
  1148. return GetRecursiveChildren(true);
  1149. }
  1150. public IReadOnlyList<BaseItem> GetRecursiveChildren(bool includeLinkedChildren)
  1151. {
  1152. return GetRecursiveChildren(i => true, includeLinkedChildren);
  1153. }
  1154. public IReadOnlyList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  1155. {
  1156. return GetRecursiveChildren(filter, true);
  1157. }
  1158. public IReadOnlyList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter, bool includeLinkedChildren)
  1159. {
  1160. var result = new Dictionary<Guid, BaseItem>();
  1161. AddChildrenToList(result, includeLinkedChildren, true, filter);
  1162. return result.Values.ToImmutableList();
  1163. }
  1164. /// <summary>
  1165. /// Adds the children to list.
  1166. /// </summary>
  1167. private void AddChildrenToList(Dictionary<Guid, BaseItem> result, bool includeLinkedChildren, bool recursive, Func<BaseItem, bool> filter)
  1168. {
  1169. foreach (var child in Children)
  1170. {
  1171. if (filter is null || filter(child))
  1172. {
  1173. result[child.Id] = child;
  1174. }
  1175. if (recursive && child.IsFolder)
  1176. {
  1177. var folder = (Folder)child;
  1178. // We can only support includeLinkedChildren for the first folder, or we might end up stuck in a loop of linked items
  1179. folder.AddChildrenToList(result, false, true, filter);
  1180. }
  1181. }
  1182. if (includeLinkedChildren)
  1183. {
  1184. foreach (var child in GetLinkedChildren())
  1185. {
  1186. if (filter is null || filter(child))
  1187. {
  1188. result[child.Id] = child;
  1189. }
  1190. }
  1191. }
  1192. }
  1193. /// <summary>
  1194. /// Gets the linked children.
  1195. /// </summary>
  1196. /// <returns>IEnumerable{BaseItem}.</returns>
  1197. public List<BaseItem> GetLinkedChildren()
  1198. {
  1199. var linkedChildren = LinkedChildren;
  1200. var list = new List<BaseItem>(linkedChildren.Length);
  1201. foreach (var i in linkedChildren)
  1202. {
  1203. var child = GetLinkedChild(i);
  1204. if (child is not null)
  1205. {
  1206. list.Add(child);
  1207. }
  1208. }
  1209. return list;
  1210. }
  1211. public bool ContainsLinkedChildByItemId(Guid itemId)
  1212. {
  1213. var linkedChildren = LinkedChildren;
  1214. foreach (var i in linkedChildren)
  1215. {
  1216. if (i.ItemId.HasValue)
  1217. {
  1218. if (i.ItemId.Value.Equals(itemId))
  1219. {
  1220. return true;
  1221. }
  1222. continue;
  1223. }
  1224. var child = GetLinkedChild(i);
  1225. if (child is not null && child.Id.Equals(itemId))
  1226. {
  1227. return true;
  1228. }
  1229. }
  1230. return false;
  1231. }
  1232. public List<BaseItem> GetLinkedChildren(User user)
  1233. {
  1234. if (!FilterLinkedChildrenPerUser || user is null)
  1235. {
  1236. return GetLinkedChildren();
  1237. }
  1238. var linkedChildren = LinkedChildren;
  1239. var list = new List<BaseItem>(linkedChildren.Length);
  1240. if (linkedChildren.Length == 0)
  1241. {
  1242. return list;
  1243. }
  1244. var allUserRootChildren = LibraryManager.GetUserRootFolder()
  1245. .GetChildren(user, true)
  1246. .OfType<Folder>()
  1247. .ToList();
  1248. var collectionFolderIds = allUserRootChildren
  1249. .Select(i => i.Id)
  1250. .ToList();
  1251. foreach (var i in linkedChildren)
  1252. {
  1253. var child = GetLinkedChild(i);
  1254. if (child is null)
  1255. {
  1256. continue;
  1257. }
  1258. var childOwner = child.GetOwner() ?? child;
  1259. if (child is not IItemByName)
  1260. {
  1261. var childProtocol = childOwner.PathProtocol;
  1262. if (!childProtocol.HasValue || childProtocol.Value != Model.MediaInfo.MediaProtocol.File)
  1263. {
  1264. if (!childOwner.IsVisibleStandalone(user))
  1265. {
  1266. continue;
  1267. }
  1268. }
  1269. else
  1270. {
  1271. var itemCollectionFolderIds =
  1272. LibraryManager.GetCollectionFolders(childOwner, allUserRootChildren).Select(f => f.Id);
  1273. if (!itemCollectionFolderIds.Any(collectionFolderIds.Contains))
  1274. {
  1275. continue;
  1276. }
  1277. }
  1278. }
  1279. list.Add(child);
  1280. }
  1281. return list;
  1282. }
  1283. /// <summary>
  1284. /// Gets the linked children.
  1285. /// </summary>
  1286. /// <returns>IEnumerable{BaseItem}.</returns>
  1287. public IReadOnlyList<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  1288. {
  1289. return LinkedChildren
  1290. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  1291. .Where(i => i.Item2 is not null)
  1292. .ToImmutableList();
  1293. }
  1294. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, IReadOnlyList<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1295. {
  1296. var changesFound = false;
  1297. if (IsFileProtocol)
  1298. {
  1299. if (RefreshLinkedChildren(fileSystemChildren))
  1300. {
  1301. changesFound = true;
  1302. }
  1303. }
  1304. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1305. return baseHasChanges || changesFound;
  1306. }
  1307. /// <summary>
  1308. /// Refreshes the linked children.
  1309. /// </summary>
  1310. /// <param name="fileSystemChildren">The enumerable of file system metadata.</param>
  1311. /// <returns><c>true</c> if the linked children were updated, <c>false</c> otherwise.</returns>
  1312. protected virtual bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  1313. {
  1314. if (SupportsShortcutChildren)
  1315. {
  1316. var newShortcutLinks = fileSystemChildren
  1317. .Where(i => !i.IsDirectory && FileSystem.IsShortcut(i.FullName))
  1318. .Select(i =>
  1319. {
  1320. try
  1321. {
  1322. Logger.LogDebug("Found shortcut at {0}", i.FullName);
  1323. var resolvedPath = CollectionFolder.ApplicationHost.ExpandVirtualPath(FileSystem.ResolveShortcut(i.FullName));
  1324. if (!string.IsNullOrEmpty(resolvedPath))
  1325. {
  1326. return new LinkedChild
  1327. {
  1328. Path = resolvedPath,
  1329. Type = LinkedChildType.Shortcut
  1330. };
  1331. }
  1332. Logger.LogError("Error resolving shortcut {0}", i.FullName);
  1333. return null;
  1334. }
  1335. catch (IOException ex)
  1336. {
  1337. Logger.LogError(ex, "Error resolving shortcut {0}", i.FullName);
  1338. return null;
  1339. }
  1340. })
  1341. .Where(i => i is not null)
  1342. .ToList();
  1343. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1344. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer(FileSystem)))
  1345. {
  1346. Logger.LogInformation("Shortcut links have changed for {0}", Path);
  1347. newShortcutLinks.AddRange(LinkedChildren.Where(i => i.Type == LinkedChildType.Manual));
  1348. LinkedChildren = newShortcutLinks.ToArray();
  1349. return true;
  1350. }
  1351. }
  1352. foreach (var child in LinkedChildren)
  1353. {
  1354. // Reset the cached value
  1355. child.ItemId = null;
  1356. }
  1357. return false;
  1358. }
  1359. /// <summary>
  1360. /// Marks the played.
  1361. /// </summary>
  1362. /// <param name="user">The user.</param>
  1363. /// <param name="datePlayed">The date played.</param>
  1364. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1365. public override void MarkPlayed(
  1366. User user,
  1367. DateTime? datePlayed,
  1368. bool resetPosition)
  1369. {
  1370. var query = new InternalItemsQuery
  1371. {
  1372. User = user,
  1373. Recursive = true,
  1374. IsFolder = false,
  1375. EnableTotalRecordCount = false
  1376. };
  1377. if (!user.DisplayMissingEpisodes)
  1378. {
  1379. query.IsVirtualItem = false;
  1380. }
  1381. var itemsResult = GetItemList(query);
  1382. // Sweep through recursively and update status
  1383. foreach (var item in itemsResult)
  1384. {
  1385. if (item.IsVirtualItem)
  1386. {
  1387. // The querying doesn't support virtual unaired
  1388. var episode = item as Episode;
  1389. if (episode is not null && episode.IsUnaired)
  1390. {
  1391. continue;
  1392. }
  1393. }
  1394. item.MarkPlayed(user, datePlayed, resetPosition);
  1395. }
  1396. }
  1397. /// <summary>
  1398. /// Marks the unplayed.
  1399. /// </summary>
  1400. /// <param name="user">The user.</param>
  1401. public override void MarkUnplayed(User user)
  1402. {
  1403. var itemsResult = GetItemList(new InternalItemsQuery
  1404. {
  1405. User = user,
  1406. Recursive = true,
  1407. IsFolder = false,
  1408. EnableTotalRecordCount = false
  1409. });
  1410. // Sweep through recursively and update status
  1411. foreach (var item in itemsResult)
  1412. {
  1413. item.MarkUnplayed(user);
  1414. }
  1415. }
  1416. public override bool IsPlayed(User user)
  1417. {
  1418. var itemsResult = GetItemList(new InternalItemsQuery(user)
  1419. {
  1420. Recursive = true,
  1421. IsFolder = false,
  1422. IsVirtualItem = false,
  1423. EnableTotalRecordCount = false
  1424. });
  1425. return itemsResult
  1426. .All(i => i.IsPlayed(user));
  1427. }
  1428. public override bool IsUnplayed(User user)
  1429. {
  1430. return !IsPlayed(user);
  1431. }
  1432. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields)
  1433. {
  1434. if (!SupportsUserDataFromChildren)
  1435. {
  1436. return;
  1437. }
  1438. if (itemDto is not null && fields.ContainsField(ItemFields.RecursiveItemCount))
  1439. {
  1440. itemDto.RecursiveItemCount = GetRecursiveChildCount(user);
  1441. }
  1442. if (SupportsPlayedStatus)
  1443. {
  1444. var unplayedQueryResult = GetItems(new InternalItemsQuery(user)
  1445. {
  1446. Recursive = true,
  1447. IsFolder = false,
  1448. IsVirtualItem = false,
  1449. EnableTotalRecordCount = true,
  1450. Limit = 0,
  1451. IsPlayed = false,
  1452. DtoOptions = new DtoOptions(false)
  1453. {
  1454. EnableImages = false
  1455. }
  1456. }).TotalRecordCount;
  1457. dto.UnplayedItemCount = unplayedQueryResult;
  1458. if (itemDto?.RecursiveItemCount > 0)
  1459. {
  1460. var unplayedPercentage = ((double)unplayedQueryResult / itemDto.RecursiveItemCount.Value) * 100;
  1461. dto.PlayedPercentage = 100 - unplayedPercentage;
  1462. dto.Played = dto.PlayedPercentage.Value >= 100;
  1463. }
  1464. else
  1465. {
  1466. dto.Played = (dto.UnplayedItemCount ?? 0) == 0;
  1467. }
  1468. }
  1469. }
  1470. /// <summary>
  1471. /// Contains constants used when reporting scan progress.
  1472. /// </summary>
  1473. private static class ProgressHelpers
  1474. {
  1475. /// <summary>
  1476. /// Reported after the folders immediate children are retrieved.
  1477. /// </summary>
  1478. public const int RetrievedChildren = 5;
  1479. /// <summary>
  1480. /// Reported after add, updating, or deleting child items from the LibraryManager.
  1481. /// </summary>
  1482. public const int UpdatedChildItems = 10;
  1483. /// <summary>
  1484. /// Reported once subfolders are scanned.
  1485. /// When scanning subfolders, the progress will be between [UpdatedItems, ScannedSubfolders].
  1486. /// </summary>
  1487. public const int ScannedSubfolders = 50;
  1488. /// <summary>
  1489. /// Reported once metadata is refreshed.
  1490. /// When refreshing metadata, the progress will be between [ScannedSubfolders, MetadataRefreshed].
  1491. /// </summary>
  1492. public const int RefreshedMetadata = 100;
  1493. /// <summary>
  1494. /// Gets the current progress given the previous step, next step, and progress in between.
  1495. /// </summary>
  1496. /// <param name="previousProgressStep">The previous progress step.</param>
  1497. /// <param name="nextProgressStep">The next progress step.</param>
  1498. /// <param name="currentProgress">The current progress step.</param>
  1499. /// <returns>The progress.</returns>
  1500. public static double GetProgress(int previousProgressStep, int nextProgressStep, double currentProgress)
  1501. {
  1502. return previousProgressStep + ((nextProgressStep - previousProgressStep) * (currentProgress / 100));
  1503. }
  1504. }
  1505. }
  1506. }