Folder.cs 58 KB

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