Folder.cs 59 KB

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