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