Folder.cs 59 KB

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