Folder.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836
  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. query.StartIndex,
  655. totalCount,
  656. returnItems.ToArray());
  657. }
  658. private bool RequiresPostFiltering2(InternalItemsQuery query)
  659. {
  660. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes[0] == BaseItemKind.BoxSet)
  661. {
  662. Logger.LogDebug("Query requires post-filtering due to BoxSet query");
  663. return true;
  664. }
  665. return false;
  666. }
  667. private bool RequiresPostFiltering(InternalItemsQuery query)
  668. {
  669. if (LinkedChildren.Length > 0)
  670. {
  671. if (this is not ICollectionFolder)
  672. {
  673. Logger.LogDebug("{Type}: Query requires post-filtering due to LinkedChildren.", GetType().Name);
  674. return true;
  675. }
  676. }
  677. // Filter by Video3DFormat
  678. if (query.Is3D.HasValue)
  679. {
  680. Logger.LogDebug("Query requires post-filtering due to Is3D");
  681. return true;
  682. }
  683. if (query.HasOfficialRating.HasValue)
  684. {
  685. Logger.LogDebug("Query requires post-filtering due to HasOfficialRating");
  686. return true;
  687. }
  688. if (query.IsPlaceHolder.HasValue)
  689. {
  690. Logger.LogDebug("Query requires post-filtering due to IsPlaceHolder");
  691. return true;
  692. }
  693. if (query.HasSpecialFeature.HasValue)
  694. {
  695. Logger.LogDebug("Query requires post-filtering due to HasSpecialFeature");
  696. return true;
  697. }
  698. if (query.HasSubtitles.HasValue)
  699. {
  700. Logger.LogDebug("Query requires post-filtering due to HasSubtitles");
  701. return true;
  702. }
  703. if (query.HasTrailer.HasValue)
  704. {
  705. Logger.LogDebug("Query requires post-filtering due to HasTrailer");
  706. return true;
  707. }
  708. // Filter by VideoType
  709. if (query.VideoTypes.Length > 0)
  710. {
  711. Logger.LogDebug("Query requires post-filtering due to VideoTypes");
  712. return true;
  713. }
  714. if (CollapseBoxSetItems(query, this, query.User, ConfigurationManager))
  715. {
  716. Logger.LogDebug("Query requires post-filtering due to CollapseBoxSetItems");
  717. return true;
  718. }
  719. if (!string.IsNullOrEmpty(query.AdjacentTo))
  720. {
  721. Logger.LogDebug("Query requires post-filtering due to AdjacentTo");
  722. return true;
  723. }
  724. if (query.SeriesStatuses.Length > 0)
  725. {
  726. Logger.LogDebug("Query requires post-filtering due to SeriesStatuses");
  727. return true;
  728. }
  729. if (query.AiredDuringSeason.HasValue)
  730. {
  731. Logger.LogDebug("Query requires post-filtering due to AiredDuringSeason");
  732. return true;
  733. }
  734. if (query.IsPlayed.HasValue)
  735. {
  736. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(BaseItemKind.Series))
  737. {
  738. Logger.LogDebug("Query requires post-filtering due to IsPlayed");
  739. return true;
  740. }
  741. }
  742. return false;
  743. }
  744. private static BaseItem[] SortItemsByRequest(InternalItemsQuery query, IReadOnlyList<BaseItem> items)
  745. {
  746. var ids = query.ItemIds;
  747. int size = items.Count;
  748. // ids can potentially contain non-unique guids, but query result cannot,
  749. // so we include only first occurrence of each guid
  750. var positions = new Dictionary<Guid, int>(size);
  751. int index = 0;
  752. for (int i = 0; i < ids.Length; i++)
  753. {
  754. if (positions.TryAdd(ids[i], index))
  755. {
  756. index++;
  757. }
  758. }
  759. var newItems = new BaseItem[size];
  760. for (int i = 0; i < size; i++)
  761. {
  762. var item = items[i];
  763. newItems[positions[item.Id]] = item;
  764. }
  765. return newItems;
  766. }
  767. public QueryResult<BaseItem> GetItems(InternalItemsQuery query)
  768. {
  769. if (query.ItemIds.Length > 0)
  770. {
  771. var result = LibraryManager.GetItemsResult(query);
  772. if (query.OrderBy.Count == 0 && query.ItemIds.Length > 1)
  773. {
  774. result.Items = SortItemsByRequest(query, result.Items);
  775. }
  776. return result;
  777. }
  778. return GetItemsInternal(query);
  779. }
  780. public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query)
  781. {
  782. query.EnableTotalRecordCount = false;
  783. if (query.ItemIds.Length > 0)
  784. {
  785. var result = LibraryManager.GetItemList(query);
  786. if (query.OrderBy.Count == 0 && query.ItemIds.Length > 1)
  787. {
  788. return SortItemsByRequest(query, result);
  789. }
  790. return result;
  791. }
  792. return GetItemsInternal(query).Items;
  793. }
  794. protected virtual QueryResult<BaseItem> GetItemsInternal(InternalItemsQuery query)
  795. {
  796. if (SourceType == SourceType.Channel)
  797. {
  798. try
  799. {
  800. query.Parent = this;
  801. query.ChannelIds = new[] { ChannelId };
  802. // Don't blow up here because it could cause parent screens with other content to fail
  803. return ChannelManager.GetChannelItemsInternal(query, new SimpleProgress<double>(), CancellationToken.None).GetAwaiter().GetResult();
  804. }
  805. catch
  806. {
  807. // Already logged at lower levels
  808. return new QueryResult<BaseItem>();
  809. }
  810. }
  811. if (query.Recursive)
  812. {
  813. return QueryRecursive(query);
  814. }
  815. var user = query.User;
  816. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  817. IEnumerable<BaseItem> items;
  818. if (query.User == null)
  819. {
  820. items = Children.Where(filter);
  821. }
  822. else
  823. {
  824. // need to pass this param to the children.
  825. var childQuery = new InternalItemsQuery
  826. {
  827. DisplayAlbumFolders = query.DisplayAlbumFolders
  828. };
  829. items = GetChildren(user, true, childQuery).Where(filter);
  830. }
  831. return PostFilterAndSort(items, query, true);
  832. }
  833. protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query, bool enableSorting)
  834. {
  835. var user = query.User;
  836. // Check recursive - don't substitute in plain folder views
  837. if (user != null)
  838. {
  839. items = CollapseBoxSetItemsIfNeeded(items, query, this, user, ConfigurationManager, CollectionManager);
  840. }
  841. #pragma warning disable CA1309
  842. if (!string.IsNullOrEmpty(query.NameStartsWithOrGreater))
  843. {
  844. items = items.Where(i => string.Compare(query.NameStartsWithOrGreater, i.SortName, StringComparison.InvariantCultureIgnoreCase) < 1);
  845. }
  846. if (!string.IsNullOrEmpty(query.NameStartsWith))
  847. {
  848. items = items.Where(i => i.SortName.StartsWith(query.NameStartsWith, StringComparison.InvariantCultureIgnoreCase));
  849. }
  850. if (!string.IsNullOrEmpty(query.NameLessThan))
  851. {
  852. items = items.Where(i => string.Compare(query.NameLessThan, i.SortName, StringComparison.InvariantCultureIgnoreCase) == 1);
  853. }
  854. #pragma warning restore CA1309
  855. // This must be the last filter
  856. if (!string.IsNullOrEmpty(query.AdjacentTo))
  857. {
  858. items = UserViewBuilder.FilterForAdjacency(items.ToList(), query.AdjacentTo);
  859. }
  860. return UserViewBuilder.SortAndPage(items, null, query, LibraryManager, enableSorting);
  861. }
  862. private static IEnumerable<BaseItem> CollapseBoxSetItemsIfNeeded(
  863. IEnumerable<BaseItem> items,
  864. InternalItemsQuery query,
  865. BaseItem queryParent,
  866. User user,
  867. IServerConfigurationManager configurationManager,
  868. ICollectionManager collectionManager)
  869. {
  870. if (items == null)
  871. {
  872. throw new ArgumentNullException(nameof(items));
  873. }
  874. if (CollapseBoxSetItems(query, queryParent, user, configurationManager))
  875. {
  876. items = collectionManager.CollapseItemsWithinBoxSets(items, user);
  877. }
  878. return items;
  879. }
  880. private static bool CollapseBoxSetItems(
  881. InternalItemsQuery query,
  882. BaseItem queryParent,
  883. User user,
  884. IServerConfigurationManager configurationManager)
  885. {
  886. // Could end up stuck in a loop like this
  887. if (queryParent is BoxSet)
  888. {
  889. return false;
  890. }
  891. if (queryParent is Series)
  892. {
  893. return false;
  894. }
  895. if (queryParent is Season)
  896. {
  897. return false;
  898. }
  899. if (queryParent is MusicAlbum)
  900. {
  901. return false;
  902. }
  903. if (queryParent is MusicArtist)
  904. {
  905. return false;
  906. }
  907. var param = query.CollapseBoxSetItems;
  908. if (!param.HasValue)
  909. {
  910. if (user != null && !configurationManager.Configuration.EnableGroupingIntoCollections)
  911. {
  912. return false;
  913. }
  914. if (query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains(BaseItemKind.Movie))
  915. {
  916. param = true;
  917. }
  918. }
  919. return param.HasValue && param.Value && AllowBoxSetCollapsing(query);
  920. }
  921. private static bool AllowBoxSetCollapsing(InternalItemsQuery request)
  922. {
  923. if (request.IsFavorite.HasValue)
  924. {
  925. return false;
  926. }
  927. if (request.IsFavoriteOrLiked.HasValue)
  928. {
  929. return false;
  930. }
  931. if (request.IsLiked.HasValue)
  932. {
  933. return false;
  934. }
  935. if (request.IsPlayed.HasValue)
  936. {
  937. return false;
  938. }
  939. if (request.IsResumable.HasValue)
  940. {
  941. return false;
  942. }
  943. if (request.IsFolder.HasValue)
  944. {
  945. return false;
  946. }
  947. if (request.Genres.Count > 0)
  948. {
  949. return false;
  950. }
  951. if (request.GenreIds.Count > 0)
  952. {
  953. return false;
  954. }
  955. if (request.HasImdbId.HasValue)
  956. {
  957. return false;
  958. }
  959. if (request.HasOfficialRating.HasValue)
  960. {
  961. return false;
  962. }
  963. if (request.HasOverview.HasValue)
  964. {
  965. return false;
  966. }
  967. if (request.HasParentalRating.HasValue)
  968. {
  969. return false;
  970. }
  971. if (request.HasSpecialFeature.HasValue)
  972. {
  973. return false;
  974. }
  975. if (request.HasSubtitles.HasValue)
  976. {
  977. return false;
  978. }
  979. if (request.HasThemeSong.HasValue)
  980. {
  981. return false;
  982. }
  983. if (request.HasThemeVideo.HasValue)
  984. {
  985. return false;
  986. }
  987. if (request.HasTmdbId.HasValue)
  988. {
  989. return false;
  990. }
  991. if (request.HasTrailer.HasValue)
  992. {
  993. return false;
  994. }
  995. if (request.ImageTypes.Length > 0)
  996. {
  997. return false;
  998. }
  999. if (request.Is3D.HasValue)
  1000. {
  1001. return false;
  1002. }
  1003. if (request.IsHD.HasValue)
  1004. {
  1005. return false;
  1006. }
  1007. if (request.IsLocked.HasValue)
  1008. {
  1009. return false;
  1010. }
  1011. if (request.IsPlaceHolder.HasValue)
  1012. {
  1013. return false;
  1014. }
  1015. if (request.IsPlayed.HasValue)
  1016. {
  1017. return false;
  1018. }
  1019. if (!string.IsNullOrWhiteSpace(request.Person))
  1020. {
  1021. return false;
  1022. }
  1023. if (request.PersonIds.Length > 0)
  1024. {
  1025. return false;
  1026. }
  1027. if (request.ItemIds.Length > 0)
  1028. {
  1029. return false;
  1030. }
  1031. if (request.StudioIds.Length > 0)
  1032. {
  1033. return false;
  1034. }
  1035. if (request.GenreIds.Count > 0)
  1036. {
  1037. return false;
  1038. }
  1039. if (request.VideoTypes.Length > 0)
  1040. {
  1041. return false;
  1042. }
  1043. if (request.Years.Length > 0)
  1044. {
  1045. return false;
  1046. }
  1047. if (request.Tags.Length > 0)
  1048. {
  1049. return false;
  1050. }
  1051. if (request.OfficialRatings.Length > 0)
  1052. {
  1053. return false;
  1054. }
  1055. if (request.MinCommunityRating.HasValue)
  1056. {
  1057. return false;
  1058. }
  1059. if (request.MinCriticRating.HasValue)
  1060. {
  1061. return false;
  1062. }
  1063. if (request.MinIndexNumber.HasValue)
  1064. {
  1065. return false;
  1066. }
  1067. return true;
  1068. }
  1069. public List<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  1070. {
  1071. if (user == null)
  1072. {
  1073. throw new ArgumentNullException(nameof(user));
  1074. }
  1075. return GetChildren(user, includeLinkedChildren, null);
  1076. }
  1077. public virtual List<BaseItem> GetChildren(User user, bool includeLinkedChildren, InternalItemsQuery query)
  1078. {
  1079. if (user == null)
  1080. {
  1081. throw new ArgumentNullException(nameof(user));
  1082. }
  1083. // the true root should return our users root folder children
  1084. if (IsPhysicalRoot)
  1085. {
  1086. return LibraryManager.GetUserRootFolder().GetChildren(user, includeLinkedChildren);
  1087. }
  1088. var result = new Dictionary<Guid, BaseItem>();
  1089. AddChildren(user, includeLinkedChildren, result, false, query);
  1090. return result.Values.ToList();
  1091. }
  1092. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  1093. {
  1094. return Children;
  1095. }
  1096. /// <summary>
  1097. /// Adds the children to list.
  1098. /// </summary>
  1099. private void AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, InternalItemsQuery query)
  1100. {
  1101. // If Query.AlbumFolders is set, then enforce the format as per the db in that it permits sub-folders in music albums.
  1102. IEnumerable<BaseItem> children = null;
  1103. if ((query?.DisplayAlbumFolders ?? false) && (this is MusicAlbum))
  1104. {
  1105. children = Children;
  1106. query = null;
  1107. }
  1108. // If there are not sub-folders, proceed as normal.
  1109. if (children == null)
  1110. {
  1111. children = GetEligibleChildrenForRecursiveChildren(user);
  1112. }
  1113. foreach (var child in children)
  1114. {
  1115. bool? isVisibleToUser = null;
  1116. if (query == null || UserViewBuilder.FilterItem(child, query))
  1117. {
  1118. isVisibleToUser = child.IsVisible(user);
  1119. if (isVisibleToUser.Value)
  1120. {
  1121. result[child.Id] = child;
  1122. }
  1123. }
  1124. if (isVisibleToUser ?? child.IsVisible(user))
  1125. {
  1126. if (recursive && child.IsFolder)
  1127. {
  1128. var folder = (Folder)child;
  1129. folder.AddChildren(user, includeLinkedChildren, result, true, query);
  1130. }
  1131. }
  1132. }
  1133. if (includeLinkedChildren)
  1134. {
  1135. foreach (var child in GetLinkedChildren(user))
  1136. {
  1137. if (query == null || UserViewBuilder.FilterItem(child, query))
  1138. {
  1139. if (child.IsVisible(user))
  1140. {
  1141. result[child.Id] = child;
  1142. }
  1143. }
  1144. }
  1145. }
  1146. }
  1147. public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query)
  1148. {
  1149. if (user == null)
  1150. {
  1151. throw new ArgumentNullException(nameof(user));
  1152. }
  1153. var result = new Dictionary<Guid, BaseItem>();
  1154. AddChildren(user, true, result, true, query);
  1155. return result.Values;
  1156. }
  1157. /// <summary>
  1158. /// Gets the recursive children.
  1159. /// </summary>
  1160. /// <returns>IList{BaseItem}.</returns>
  1161. public IList<BaseItem> GetRecursiveChildren()
  1162. {
  1163. return GetRecursiveChildren(true);
  1164. }
  1165. public IList<BaseItem> GetRecursiveChildren(bool includeLinkedChildren)
  1166. {
  1167. return GetRecursiveChildren(i => true, includeLinkedChildren);
  1168. }
  1169. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  1170. {
  1171. return GetRecursiveChildren(filter, true);
  1172. }
  1173. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter, bool includeLinkedChildren)
  1174. {
  1175. var result = new Dictionary<Guid, BaseItem>();
  1176. AddChildrenToList(result, includeLinkedChildren, true, filter);
  1177. return result.Values.ToList();
  1178. }
  1179. /// <summary>
  1180. /// Adds the children to list.
  1181. /// </summary>
  1182. private void AddChildrenToList(Dictionary<Guid, BaseItem> result, bool includeLinkedChildren, bool recursive, Func<BaseItem, bool> filter)
  1183. {
  1184. foreach (var child in Children)
  1185. {
  1186. if (filter == null || filter(child))
  1187. {
  1188. result[child.Id] = child;
  1189. }
  1190. if (recursive && child.IsFolder)
  1191. {
  1192. var folder = (Folder)child;
  1193. // We can only support includeLinkedChildren for the first folder, or we might end up stuck in a loop of linked items
  1194. folder.AddChildrenToList(result, false, true, filter);
  1195. }
  1196. }
  1197. if (includeLinkedChildren)
  1198. {
  1199. foreach (var child in GetLinkedChildren())
  1200. {
  1201. if (filter == null || filter(child))
  1202. {
  1203. result[child.Id] = child;
  1204. }
  1205. }
  1206. }
  1207. }
  1208. /// <summary>
  1209. /// Gets the linked children.
  1210. /// </summary>
  1211. /// <returns>IEnumerable{BaseItem}.</returns>
  1212. public List<BaseItem> GetLinkedChildren()
  1213. {
  1214. var linkedChildren = LinkedChildren;
  1215. var list = new List<BaseItem>(linkedChildren.Length);
  1216. foreach (var i in linkedChildren)
  1217. {
  1218. var child = GetLinkedChild(i);
  1219. if (child != null)
  1220. {
  1221. list.Add(child);
  1222. }
  1223. }
  1224. return list;
  1225. }
  1226. public bool ContainsLinkedChildByItemId(Guid itemId)
  1227. {
  1228. var linkedChildren = LinkedChildren;
  1229. foreach (var i in linkedChildren)
  1230. {
  1231. if (i.ItemId.HasValue)
  1232. {
  1233. if (i.ItemId.Value == itemId)
  1234. {
  1235. return true;
  1236. }
  1237. continue;
  1238. }
  1239. var child = GetLinkedChild(i);
  1240. if (child != null && child.Id == itemId)
  1241. {
  1242. return true;
  1243. }
  1244. }
  1245. return false;
  1246. }
  1247. public List<BaseItem> GetLinkedChildren(User user)
  1248. {
  1249. if (!FilterLinkedChildrenPerUser || user == null)
  1250. {
  1251. return GetLinkedChildren();
  1252. }
  1253. var linkedChildren = LinkedChildren;
  1254. var list = new List<BaseItem>(linkedChildren.Length);
  1255. if (linkedChildren.Length == 0)
  1256. {
  1257. return list;
  1258. }
  1259. var allUserRootChildren = LibraryManager.GetUserRootFolder()
  1260. .GetChildren(user, true)
  1261. .OfType<Folder>()
  1262. .ToList();
  1263. var collectionFolderIds = allUserRootChildren
  1264. .Select(i => i.Id)
  1265. .ToList();
  1266. foreach (var i in linkedChildren)
  1267. {
  1268. var child = GetLinkedChild(i);
  1269. if (child == null)
  1270. {
  1271. continue;
  1272. }
  1273. var childOwner = child.GetOwner() ?? child;
  1274. if (child is not IItemByName)
  1275. {
  1276. var childProtocol = childOwner.PathProtocol;
  1277. if (!childProtocol.HasValue || childProtocol.Value != Model.MediaInfo.MediaProtocol.File)
  1278. {
  1279. if (!childOwner.IsVisibleStandalone(user))
  1280. {
  1281. continue;
  1282. }
  1283. }
  1284. else
  1285. {
  1286. var itemCollectionFolderIds =
  1287. LibraryManager.GetCollectionFolders(childOwner, allUserRootChildren).Select(f => f.Id);
  1288. if (!itemCollectionFolderIds.Any(collectionFolderIds.Contains))
  1289. {
  1290. continue;
  1291. }
  1292. }
  1293. }
  1294. list.Add(child);
  1295. }
  1296. return list;
  1297. }
  1298. /// <summary>
  1299. /// Gets the linked children.
  1300. /// </summary>
  1301. /// <returns>IEnumerable{BaseItem}.</returns>
  1302. public IEnumerable<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  1303. {
  1304. return LinkedChildren
  1305. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  1306. .Where(i => i.Item2 != null);
  1307. }
  1308. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1309. {
  1310. var changesFound = false;
  1311. if (IsFileProtocol)
  1312. {
  1313. if (RefreshLinkedChildren(fileSystemChildren))
  1314. {
  1315. changesFound = true;
  1316. }
  1317. }
  1318. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1319. return baseHasChanges || changesFound;
  1320. }
  1321. /// <summary>
  1322. /// Refreshes the linked children.
  1323. /// </summary>
  1324. /// <param name="fileSystemChildren">The enumerable of file system metadata.</param>
  1325. /// <returns><c>true</c> if the linked children were updated, <c>false</c> otherwise.</returns>
  1326. protected virtual bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  1327. {
  1328. if (SupportsShortcutChildren)
  1329. {
  1330. var newShortcutLinks = fileSystemChildren
  1331. .Where(i => !i.IsDirectory && FileSystem.IsShortcut(i.FullName))
  1332. .Select(i =>
  1333. {
  1334. try
  1335. {
  1336. Logger.LogDebug("Found shortcut at {0}", i.FullName);
  1337. var resolvedPath = CollectionFolder.ApplicationHost.ExpandVirtualPath(FileSystem.ResolveShortcut(i.FullName));
  1338. if (!string.IsNullOrEmpty(resolvedPath))
  1339. {
  1340. return new LinkedChild
  1341. {
  1342. Path = resolvedPath,
  1343. Type = LinkedChildType.Shortcut
  1344. };
  1345. }
  1346. Logger.LogError("Error resolving shortcut {0}", i.FullName);
  1347. return null;
  1348. }
  1349. catch (IOException ex)
  1350. {
  1351. Logger.LogError(ex, "Error resolving shortcut {0}", i.FullName);
  1352. return null;
  1353. }
  1354. })
  1355. .Where(i => i != null)
  1356. .ToList();
  1357. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1358. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer(FileSystem)))
  1359. {
  1360. Logger.LogInformation("Shortcut links have changed for {0}", Path);
  1361. newShortcutLinks.AddRange(LinkedChildren.Where(i => i.Type == LinkedChildType.Manual));
  1362. LinkedChildren = newShortcutLinks.ToArray();
  1363. return true;
  1364. }
  1365. }
  1366. foreach (var child in LinkedChildren)
  1367. {
  1368. // Reset the cached value
  1369. child.ItemId = null;
  1370. }
  1371. return false;
  1372. }
  1373. /// <summary>
  1374. /// Marks the played.
  1375. /// </summary>
  1376. /// <param name="user">The user.</param>
  1377. /// <param name="datePlayed">The date played.</param>
  1378. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1379. public override void MarkPlayed(
  1380. User user,
  1381. DateTime? datePlayed,
  1382. bool resetPosition)
  1383. {
  1384. var query = new InternalItemsQuery
  1385. {
  1386. User = user,
  1387. Recursive = true,
  1388. IsFolder = false,
  1389. EnableTotalRecordCount = false
  1390. };
  1391. if (!user.DisplayMissingEpisodes)
  1392. {
  1393. query.IsVirtualItem = false;
  1394. }
  1395. var itemsResult = GetItemList(query);
  1396. // Sweep through recursively and update status
  1397. foreach (var item in itemsResult)
  1398. {
  1399. if (item.IsVirtualItem)
  1400. {
  1401. // The querying doesn't support virtual unaired
  1402. var episode = item as Episode;
  1403. if (episode != null && episode.IsUnaired)
  1404. {
  1405. continue;
  1406. }
  1407. }
  1408. item.MarkPlayed(user, datePlayed, resetPosition);
  1409. }
  1410. }
  1411. /// <summary>
  1412. /// Marks the unplayed.
  1413. /// </summary>
  1414. /// <param name="user">The user.</param>
  1415. public override void MarkUnplayed(User user)
  1416. {
  1417. var itemsResult = GetItemList(new InternalItemsQuery
  1418. {
  1419. User = user,
  1420. Recursive = true,
  1421. IsFolder = false,
  1422. EnableTotalRecordCount = false
  1423. });
  1424. // Sweep through recursively and update status
  1425. foreach (var item in itemsResult)
  1426. {
  1427. item.MarkUnplayed(user);
  1428. }
  1429. }
  1430. public override bool IsPlayed(User user)
  1431. {
  1432. var itemsResult = GetItemList(new InternalItemsQuery(user)
  1433. {
  1434. Recursive = true,
  1435. IsFolder = false,
  1436. IsVirtualItem = false,
  1437. EnableTotalRecordCount = false
  1438. });
  1439. return itemsResult
  1440. .All(i => i.IsPlayed(user));
  1441. }
  1442. public override bool IsUnplayed(User user)
  1443. {
  1444. return !IsPlayed(user);
  1445. }
  1446. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields)
  1447. {
  1448. if (!SupportsUserDataFromChildren)
  1449. {
  1450. return;
  1451. }
  1452. if (itemDto != null)
  1453. {
  1454. if (fields.ContainsField(ItemFields.RecursiveItemCount))
  1455. {
  1456. itemDto.RecursiveItemCount = GetRecursiveChildCount(user);
  1457. }
  1458. }
  1459. if (SupportsPlayedStatus)
  1460. {
  1461. var unplayedQueryResult = GetItems(new InternalItemsQuery(user)
  1462. {
  1463. Recursive = true,
  1464. IsFolder = false,
  1465. IsVirtualItem = false,
  1466. EnableTotalRecordCount = true,
  1467. Limit = 0,
  1468. IsPlayed = false,
  1469. DtoOptions = new DtoOptions(false)
  1470. {
  1471. EnableImages = false
  1472. }
  1473. }).TotalRecordCount;
  1474. dto.UnplayedItemCount = unplayedQueryResult;
  1475. if (itemDto?.RecursiveItemCount > 0)
  1476. {
  1477. var unplayedPercentage = ((double)unplayedQueryResult / itemDto.RecursiveItemCount.Value) * 100;
  1478. dto.PlayedPercentage = 100 - unplayedPercentage;
  1479. dto.Played = dto.PlayedPercentage.Value >= 100;
  1480. }
  1481. else
  1482. {
  1483. dto.Played = (dto.UnplayedItemCount ?? 0) == 0;
  1484. }
  1485. }
  1486. }
  1487. /// <summary>
  1488. /// Contains constants used when reporting scan progress.
  1489. /// </summary>
  1490. private static class ProgressHelpers
  1491. {
  1492. /// <summary>
  1493. /// Reported after the folders immediate children are retrieved.
  1494. /// </summary>
  1495. public const int RetrievedChildren = 5;
  1496. /// <summary>
  1497. /// Reported after add, updating, or deleting child items from the LibraryManager.
  1498. /// </summary>
  1499. public const int UpdatedChildItems = 10;
  1500. /// <summary>
  1501. /// Reported once subfolders are scanned.
  1502. /// When scanning subfolders, the progress will be between [UpdatedItems, ScannedSubfolders].
  1503. /// </summary>
  1504. public const int ScannedSubfolders = 50;
  1505. /// <summary>
  1506. /// Reported once metadata is refreshed.
  1507. /// When refreshing metadata, the progress will be between [ScannedSubfolders, MetadataRefreshed].
  1508. /// </summary>
  1509. public const int RefreshedMetadata = 100;
  1510. /// <summary>
  1511. /// Gets the current progress given the previous step, next step, and progress in between.
  1512. /// </summary>
  1513. /// <param name="previousProgressStep">The previous progress step.</param>
  1514. /// <param name="nextProgressStep">The next progress step.</param>
  1515. /// <param name="currentProgress">The current progress step.</param>
  1516. /// <returns>The progress.</returns>
  1517. public static double GetProgress(int previousProgressStep, int nextProgressStep, double currentProgress)
  1518. {
  1519. return previousProgressStep + ((nextProgressStep - previousProgressStep) * (currentProgress / 100));
  1520. }
  1521. }
  1522. }
  1523. }