Folder.cs 59 KB

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