Folder.cs 60 KB

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