Folder.cs 58 KB

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