Folder.cs 60 KB

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