Folder.cs 59 KB

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