Folder.cs 59 KB

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