Folder.cs 59 KB

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