Folder.cs 59 KB

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