Folder.cs 59 KB

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