2
0

Folder.cs 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835
  1. #nullable disable
  2. #pragma warning disable CA1002, CA1721, CA1819, CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text.Json.Serialization;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using System.Threading.Tasks.Dataflow;
  11. using Jellyfin.Data.Entities;
  12. using Jellyfin.Data.Enums;
  13. using MediaBrowser.Common.Progress;
  14. using MediaBrowser.Controller.Channels;
  15. using MediaBrowser.Controller.Collections;
  16. using MediaBrowser.Controller.Configuration;
  17. using MediaBrowser.Controller.Dto;
  18. using MediaBrowser.Controller.Entities.Audio;
  19. using MediaBrowser.Controller.Entities.Movies;
  20. using MediaBrowser.Controller.Library;
  21. using MediaBrowser.Controller.Providers;
  22. using MediaBrowser.Model.Dto;
  23. using MediaBrowser.Model.IO;
  24. using MediaBrowser.Model.Querying;
  25. using Microsoft.Extensions.Logging;
  26. using Episode = MediaBrowser.Controller.Entities.TV.Episode;
  27. using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
  28. using Season = MediaBrowser.Controller.Entities.TV.Season;
  29. using Series = MediaBrowser.Controller.Entities.TV.Series;
  30. namespace MediaBrowser.Controller.Entities
  31. {
  32. /// <summary>
  33. /// Class Folder.
  34. /// </summary>
  35. public class Folder : BaseItem
  36. {
  37. public Folder()
  38. {
  39. LinkedChildren = Array.Empty<LinkedChild>();
  40. }
  41. public static IUserViewManager UserViewManager { get; set; }
  42. /// <summary>
  43. /// Gets or sets a value indicating whether this instance is root.
  44. /// </summary>
  45. /// <value><c>true</c> if this instance is root; otherwise, <c>false</c>.</value>
  46. public bool IsRoot { get; set; }
  47. public LinkedChild[] LinkedChildren { get; set; }
  48. [JsonIgnore]
  49. public DateTime? DateLastMediaAdded { get; set; }
  50. [JsonIgnore]
  51. public override bool SupportsThemeMedia => true;
  52. [JsonIgnore]
  53. public virtual bool IsPreSorted => false;
  54. [JsonIgnore]
  55. public virtual bool IsPhysicalRoot => false;
  56. [JsonIgnore]
  57. public override bool SupportsInheritedParentImages => true;
  58. [JsonIgnore]
  59. public override bool SupportsPlayedStatus => true;
  60. /// <summary>
  61. /// Gets a value indicating whether this instance is folder.
  62. /// </summary>
  63. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  64. [JsonIgnore]
  65. public override bool IsFolder => true;
  66. [JsonIgnore]
  67. public override bool IsDisplayedAsFolder => true;
  68. [JsonIgnore]
  69. public virtual bool SupportsCumulativeRunTimeTicks => false;
  70. [JsonIgnore]
  71. public virtual bool SupportsDateLastMediaAdded => false;
  72. [JsonIgnore]
  73. public override string FileNameWithoutExtension
  74. {
  75. get
  76. {
  77. if (IsFileProtocol)
  78. {
  79. return System.IO.Path.GetFileName(Path);
  80. }
  81. return null;
  82. }
  83. }
  84. /// <summary>
  85. /// Gets the actual children.
  86. /// </summary>
  87. /// <value>The actual children.</value>
  88. [JsonIgnore]
  89. public virtual IEnumerable<BaseItem> Children => LoadChildren();
  90. /// <summary>
  91. /// Gets thread-safe access to all recursive children of this folder - without regard to user.
  92. /// </summary>
  93. /// <value>The recursive children.</value>
  94. [JsonIgnore]
  95. public IEnumerable<BaseItem> RecursiveChildren => GetRecursiveChildren();
  96. [JsonIgnore]
  97. protected virtual bool SupportsShortcutChildren => false;
  98. protected virtual bool FilterLinkedChildrenPerUser => false;
  99. [JsonIgnore]
  100. protected override bool SupportsOwnedItems => base.SupportsOwnedItems || SupportsShortcutChildren;
  101. [JsonIgnore]
  102. public virtual bool SupportsUserDataFromChildren
  103. {
  104. get
  105. {
  106. // These are just far too slow.
  107. if (this is ICollectionFolder)
  108. {
  109. return false;
  110. }
  111. if (this is UserView)
  112. {
  113. return false;
  114. }
  115. if (this is UserRootFolder)
  116. {
  117. return false;
  118. }
  119. if (this is Channel)
  120. {
  121. return false;
  122. }
  123. if (SourceType != SourceType.Library)
  124. {
  125. return false;
  126. }
  127. if (this is IItemByName)
  128. {
  129. if (this is not IHasDualAccess hasDualAccess || hasDualAccess.IsAccessedByName)
  130. {
  131. return false;
  132. }
  133. }
  134. return true;
  135. }
  136. }
  137. public static ICollectionManager CollectionManager { get; set; }
  138. public override bool CanDelete()
  139. {
  140. if (IsRoot)
  141. {
  142. return false;
  143. }
  144. return base.CanDelete();
  145. }
  146. public override bool RequiresRefresh()
  147. {
  148. var baseResult = base.RequiresRefresh();
  149. if (SupportsCumulativeRunTimeTicks && !RunTimeTicks.HasValue)
  150. {
  151. baseResult = true;
  152. }
  153. return baseResult;
  154. }
  155. /// <summary>
  156. /// Adds the child.
  157. /// </summary>
  158. /// <param name="item">The item.</param>
  159. /// <exception cref="InvalidOperationException">Unable to add + item.Name.</exception>
  160. public void AddChild(BaseItem item)
  161. {
  162. item.SetParent(this);
  163. if (item.Id.Equals(default))
  164. {
  165. item.Id = LibraryManager.GetNewItemId(item.Path, item.GetType());
  166. }
  167. if (item.DateCreated == DateTime.MinValue)
  168. {
  169. item.DateCreated = DateTime.UtcNow;
  170. }
  171. if (item.DateModified == DateTime.MinValue)
  172. {
  173. item.DateModified = DateTime.UtcNow;
  174. }
  175. LibraryManager.CreateItem(item, this);
  176. }
  177. public override bool IsVisible(User user)
  178. {
  179. if (this is ICollectionFolder && this is not BasePluginFolder)
  180. {
  181. var blockedMediaFolders = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedMediaFolders);
  182. if (blockedMediaFolders.Length > 0)
  183. {
  184. if (blockedMediaFolders.Contains(Id))
  185. {
  186. return false;
  187. }
  188. }
  189. else
  190. {
  191. if (!user.HasPermission(PermissionKind.EnableAllFolders)
  192. && !user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders).Contains(Id))
  193. {
  194. return false;
  195. }
  196. }
  197. }
  198. return base.IsVisible(user);
  199. }
  200. /// <summary>
  201. /// Loads our children. Validation will occur externally.
  202. /// We want this synchronous.
  203. /// </summary>
  204. /// <returns>Returns children.</returns>
  205. protected virtual List<BaseItem> LoadChildren()
  206. {
  207. // logger.LogDebug("Loading children from {0} {1} {2}", GetType().Name, Id, Path);
  208. // just load our children from the repo - the library will be validated and maintained in other processes
  209. return GetCachedChildren();
  210. }
  211. public override double? GetRefreshProgress()
  212. {
  213. return ProviderManager.GetRefreshProgress(Id);
  214. }
  215. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken)
  216. {
  217. return ValidateChildren(progress, new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken: cancellationToken);
  218. }
  219. /// <summary>
  220. /// Validates that the children of the folder still exist.
  221. /// </summary>
  222. /// <param name="progress">The progress.</param>
  223. /// <param name="metadataRefreshOptions">The metadata refresh options.</param>
  224. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  225. /// <param name="cancellationToken">The cancellation token.</param>
  226. /// <returns>Task.</returns>
  227. public Task ValidateChildren(IProgress<double> progress, MetadataRefreshOptions metadataRefreshOptions, bool recursive = true, CancellationToken cancellationToken = default)
  228. {
  229. return ValidateChildrenInternal(progress, recursive, true, metadataRefreshOptions, metadataRefreshOptions.DirectoryService, cancellationToken);
  230. }
  231. private Dictionary<Guid, BaseItem> GetActualChildrenDictionary()
  232. {
  233. var dictionary = new Dictionary<Guid, BaseItem>();
  234. var childrenList = Children.ToList();
  235. foreach (var child in childrenList)
  236. {
  237. var id = child.Id;
  238. if (dictionary.ContainsKey(id))
  239. {
  240. Logger.LogError(
  241. "Found folder containing items with duplicate id. Path: {Path}, Child Name: {ChildName}",
  242. Path ?? Name,
  243. child.Path ?? child.Name);
  244. }
  245. else
  246. {
  247. dictionary[id] = child;
  248. }
  249. }
  250. return dictionary;
  251. }
  252. protected override void TriggerOnRefreshStart()
  253. {
  254. }
  255. protected override void TriggerOnRefreshComplete()
  256. {
  257. }
  258. /// <summary>
  259. /// Validates the children internal.
  260. /// </summary>
  261. /// <param name="progress">The progress.</param>
  262. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  263. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  264. /// <param name="refreshOptions">The refresh options.</param>
  265. /// <param name="directoryService">The directory service.</param>
  266. /// <param name="cancellationToken">The cancellation token.</param>
  267. /// <returns>Task.</returns>
  268. protected virtual async Task ValidateChildrenInternal(IProgress<double> progress, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService, CancellationToken cancellationToken)
  269. {
  270. if (recursive)
  271. {
  272. ProviderManager.OnRefreshStart(this);
  273. }
  274. try
  275. {
  276. await ValidateChildrenInternal2(progress, recursive, refreshChildMetadata, refreshOptions, directoryService, cancellationToken).ConfigureAwait(false);
  277. }
  278. finally
  279. {
  280. if (recursive)
  281. {
  282. ProviderManager.OnRefreshComplete(this);
  283. }
  284. }
  285. }
  286. private async Task ValidateChildrenInternal2(IProgress<double> progress, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService, CancellationToken cancellationToken)
  287. {
  288. cancellationToken.ThrowIfCancellationRequested();
  289. var validChildren = new List<BaseItem>();
  290. var validChildrenNeedGeneration = false;
  291. if (IsFileProtocol)
  292. {
  293. IEnumerable<BaseItem> nonCachedChildren;
  294. try
  295. {
  296. nonCachedChildren = GetNonCachedChildren(directoryService);
  297. }
  298. catch (Exception ex)
  299. {
  300. Logger.LogError(ex, "Error retrieving children folder");
  301. return;
  302. }
  303. progress.Report(ProgressHelpers.RetrievedChildren);
  304. if (recursive)
  305. {
  306. ProviderManager.OnRefreshProgress(this, ProgressHelpers.RetrievedChildren);
  307. }
  308. // Build a dictionary of the current children we have now by Id so we can compare quickly and easily
  309. var currentChildren = GetActualChildrenDictionary();
  310. // Create a list for our validated children
  311. var newItems = new List<BaseItem>();
  312. cancellationToken.ThrowIfCancellationRequested();
  313. foreach (var child in nonCachedChildren)
  314. {
  315. if (currentChildren.TryGetValue(child.Id, out BaseItem currentChild))
  316. {
  317. validChildren.Add(currentChild);
  318. if (currentChild.UpdateFromResolvedItem(child) > ItemUpdateType.None)
  319. {
  320. await currentChild.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  321. }
  322. else
  323. {
  324. // metadata is up-to-date; make sure DB has correct images dimensions and hash
  325. await LibraryManager.UpdateImagesAsync(currentChild).ConfigureAwait(false);
  326. }
  327. continue;
  328. }
  329. // Brand new item - needs to be added
  330. child.SetParent(this);
  331. newItems.Add(child);
  332. validChildren.Add(child);
  333. }
  334. // If any items were added or removed....
  335. if (newItems.Count > 0 || currentChildren.Count != validChildren.Count)
  336. {
  337. // That's all the new and changed ones - now see if there are any that are missing
  338. var itemsRemoved = currentChildren.Values.Except(validChildren).ToList();
  339. foreach (var item in itemsRemoved)
  340. {
  341. if (item.IsFileProtocol)
  342. {
  343. Logger.LogDebug("Removed item: {Path}", item.Path);
  344. item.SetParent(null);
  345. LibraryManager.DeleteItem(item, new DeleteOptions { DeleteFileLocation = false }, this, false);
  346. }
  347. }
  348. LibraryManager.CreateItems(newItems, this, cancellationToken);
  349. }
  350. }
  351. else
  352. {
  353. validChildrenNeedGeneration = true;
  354. }
  355. progress.Report(ProgressHelpers.UpdatedChildItems);
  356. if (recursive)
  357. {
  358. ProviderManager.OnRefreshProgress(this, ProgressHelpers.UpdatedChildItems);
  359. }
  360. cancellationToken.ThrowIfCancellationRequested();
  361. if (recursive)
  362. {
  363. var innerProgress = new ActionableProgress<double>();
  364. var folder = this;
  365. innerProgress.RegisterAction(innerPercent =>
  366. {
  367. var percent = ProgressHelpers.GetProgress(ProgressHelpers.UpdatedChildItems, ProgressHelpers.ScannedSubfolders, innerPercent);
  368. progress.Report(percent);
  369. ProviderManager.OnRefreshProgress(folder, percent);
  370. });
  371. if (validChildrenNeedGeneration)
  372. {
  373. validChildren = Children.ToList();
  374. validChildrenNeedGeneration = false;
  375. }
  376. await ValidateSubFolders(validChildren.OfType<Folder>().ToList(), directoryService, innerProgress, cancellationToken).ConfigureAwait(false);
  377. }
  378. if (refreshChildMetadata)
  379. {
  380. progress.Report(ProgressHelpers.ScannedSubfolders);
  381. if (recursive)
  382. {
  383. ProviderManager.OnRefreshProgress(this, ProgressHelpers.ScannedSubfolders);
  384. }
  385. var container = this as IMetadataContainer;
  386. var innerProgress = new ActionableProgress<double>();
  387. var folder = this;
  388. innerProgress.RegisterAction(innerPercent =>
  389. {
  390. var percent = ProgressHelpers.GetProgress(ProgressHelpers.ScannedSubfolders, ProgressHelpers.RefreshedMetadata, innerPercent);
  391. progress.Report(percent);
  392. if (recursive)
  393. {
  394. ProviderManager.OnRefreshProgress(folder, percent);
  395. }
  396. });
  397. if (container != null)
  398. {
  399. await RefreshAllMetadataForContainer(container, refreshOptions, innerProgress, cancellationToken).ConfigureAwait(false);
  400. }
  401. else
  402. {
  403. if (validChildrenNeedGeneration)
  404. {
  405. validChildren = Children.ToList();
  406. }
  407. await RefreshMetadataRecursive(validChildren, refreshOptions, recursive, innerProgress, cancellationToken).ConfigureAwait(false);
  408. }
  409. }
  410. }
  411. private Task RefreshMetadataRecursive(IList<BaseItem> children, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  412. {
  413. return RunTasks(
  414. (baseItem, innerProgress) => RefreshChildMetadata(baseItem, refreshOptions, recursive && baseItem.IsFolder, innerProgress, cancellationToken),
  415. children,
  416. progress,
  417. cancellationToken);
  418. }
  419. private async Task RefreshAllMetadataForContainer(IMetadataContainer container, MetadataRefreshOptions refreshOptions, IProgress<double> progress, CancellationToken cancellationToken)
  420. {
  421. // limit the amount of concurrent metadata refreshes
  422. await ProviderManager.RunMetadataRefresh(
  423. async () =>
  424. {
  425. var series = container as Series;
  426. if (series != null)
  427. {
  428. await series.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  429. }
  430. await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  431. },
  432. cancellationToken).ConfigureAwait(false);
  433. }
  434. private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  435. {
  436. var container = child as IMetadataContainer;
  437. if (container != null)
  438. {
  439. await RefreshAllMetadataForContainer(container, refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  440. }
  441. else
  442. {
  443. if (refreshOptions.RefreshItem(child))
  444. {
  445. // limit the amount of concurrent metadata refreshes
  446. await ProviderManager.RunMetadataRefresh(
  447. async () => await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false),
  448. cancellationToken).ConfigureAwait(false);
  449. }
  450. if (recursive && child is Folder folder)
  451. {
  452. await folder.RefreshMetadataRecursive(folder.Children.ToList(), refreshOptions, true, progress, cancellationToken).ConfigureAwait(false);
  453. }
  454. }
  455. }
  456. /// <summary>
  457. /// Refreshes the children.
  458. /// </summary>
  459. /// <param name="children">The children.</param>
  460. /// <param name="directoryService">The directory service.</param>
  461. /// <param name="progress">The progress.</param>
  462. /// <param name="cancellationToken">The cancellation token.</param>
  463. /// <returns>Task.</returns>
  464. private Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
  465. {
  466. return RunTasks(
  467. (folder, innerProgress) => folder.ValidateChildrenInternal(innerProgress, true, false, null, directoryService, cancellationToken),
  468. children,
  469. progress,
  470. cancellationToken);
  471. }
  472. /// <summary>
  473. /// Runs an action block on a list of children.
  474. /// </summary>
  475. /// <param name="task">The task to run for each child.</param>
  476. /// <param name="children">The list of children.</param>
  477. /// <param name="progress">The progress.</param>
  478. /// <param name="cancellationToken">The cancellation token.</param>
  479. /// <returns>Task.</returns>
  480. private async Task RunTasks<T>(Func<T, IProgress<double>, Task> task, IList<T> children, IProgress<double> progress, CancellationToken cancellationToken)
  481. {
  482. var childrenCount = children.Count;
  483. var childrenProgress = new double[childrenCount];
  484. void UpdateProgress()
  485. {
  486. progress.Report(childrenProgress.Average());
  487. }
  488. var fanoutConcurrency = ConfigurationManager.Configuration.LibraryScanFanoutConcurrency;
  489. var parallelism = fanoutConcurrency == 0 ? Environment.ProcessorCount : fanoutConcurrency;
  490. var actionBlock = new ActionBlock<int>(
  491. async i =>
  492. {
  493. var innerProgress = new ActionableProgress<double>();
  494. innerProgress.RegisterAction(innerPercent =>
  495. {
  496. // round the percent and only update progress if it changed to prevent excessive UpdateProgress calls
  497. var innerPercentRounded = Math.Round(innerPercent);
  498. if (childrenProgress[i] != innerPercentRounded)
  499. {
  500. childrenProgress[i] = innerPercentRounded;
  501. UpdateProgress();
  502. }
  503. });
  504. await task(children[i], innerProgress).ConfigureAwait(false);
  505. childrenProgress[i] = 100;
  506. UpdateProgress();
  507. },
  508. new ExecutionDataflowBlockOptions
  509. {
  510. MaxDegreeOfParallelism = parallelism,
  511. CancellationToken = cancellationToken,
  512. });
  513. for (var i = 0; i < childrenCount; i++)
  514. {
  515. actionBlock.Post(i);
  516. }
  517. actionBlock.Complete();
  518. await actionBlock.Completion.ConfigureAwait(false);
  519. }
  520. /// <summary>
  521. /// Get the children of this folder from the actual file system.
  522. /// </summary>
  523. /// <returns>IEnumerable{BaseItem}.</returns>
  524. /// <param name="directoryService">The directory service to use for operation.</param>
  525. /// <returns>Returns set of base items.</returns>
  526. protected virtual IEnumerable<BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
  527. {
  528. var collectionType = LibraryManager.GetContentType(this);
  529. var libraryOptions = LibraryManager.GetLibraryOptions(this);
  530. return LibraryManager.ResolvePaths(GetFileSystemChildren(directoryService), directoryService, this, libraryOptions, collectionType);
  531. }
  532. /// <summary>
  533. /// Get our children from the repo - stubbed for now.
  534. /// </summary>
  535. /// <returns>IEnumerable{BaseItem}.</returns>
  536. protected List<BaseItem> GetCachedChildren()
  537. {
  538. return ItemRepository.GetItemList(new InternalItemsQuery
  539. {
  540. Parent = this,
  541. GroupByPresentationUniqueKey = false,
  542. DtoOptions = new DtoOptions(true)
  543. });
  544. }
  545. public virtual int GetChildCount(User user)
  546. {
  547. if (LinkedChildren.Length > 0)
  548. {
  549. if (this is not ICollectionFolder)
  550. {
  551. return GetChildren(user, true).Count;
  552. }
  553. }
  554. var result = GetItems(new InternalItemsQuery(user)
  555. {
  556. Recursive = false,
  557. Limit = 0,
  558. Parent = this,
  559. DtoOptions = new DtoOptions(false)
  560. {
  561. EnableImages = false
  562. }
  563. });
  564. return result.TotalRecordCount;
  565. }
  566. public virtual int GetRecursiveChildCount(User user)
  567. {
  568. return GetItems(new InternalItemsQuery(user)
  569. {
  570. Recursive = true,
  571. IsFolder = false,
  572. IsVirtualItem = false,
  573. EnableTotalRecordCount = true,
  574. Limit = 0,
  575. DtoOptions = new DtoOptions(false)
  576. {
  577. EnableImages = false
  578. }
  579. }).TotalRecordCount;
  580. }
  581. public QueryResult<BaseItem> QueryRecursive(InternalItemsQuery query)
  582. {
  583. var user = query.User;
  584. if (!query.ForceDirect && RequiresPostFiltering(query))
  585. {
  586. IEnumerable<BaseItem> items;
  587. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  588. if (query.User == null)
  589. {
  590. items = GetRecursiveChildren(filter);
  591. }
  592. else
  593. {
  594. items = GetRecursiveChildren(user, query);
  595. }
  596. return PostFilterAndSort(items, query, true);
  597. }
  598. if (this is not UserRootFolder
  599. && this is not AggregateFolder
  600. && query.ParentId.Equals(default))
  601. {
  602. query.Parent = this;
  603. }
  604. if (RequiresPostFiltering2(query))
  605. {
  606. return QueryWithPostFiltering2(query);
  607. }
  608. return LibraryManager.GetItemsResult(query);
  609. }
  610. private QueryResult<BaseItem> QueryWithPostFiltering2(InternalItemsQuery query)
  611. {
  612. var startIndex = query.StartIndex;
  613. var limit = query.Limit;
  614. query.StartIndex = null;
  615. query.Limit = null;
  616. IEnumerable<BaseItem> itemsList = LibraryManager.GetItemList(query);
  617. var user = query.User;
  618. if (user != null)
  619. {
  620. // needed for boxsets
  621. itemsList = itemsList.Where(i => i.IsVisibleStandalone(query.User));
  622. }
  623. IEnumerable<BaseItem> returnItems;
  624. int totalCount = 0;
  625. if (query.EnableTotalRecordCount)
  626. {
  627. var itemArray = itemsList.ToArray();
  628. totalCount = itemArray.Length;
  629. returnItems = itemArray;
  630. }
  631. else
  632. {
  633. returnItems = itemsList;
  634. }
  635. if (limit.HasValue)
  636. {
  637. returnItems = returnItems.Skip(startIndex ?? 0).Take(limit.Value);
  638. }
  639. else if (startIndex.HasValue)
  640. {
  641. returnItems = returnItems.Skip(startIndex.Value);
  642. }
  643. return new QueryResult<BaseItem>(
  644. query.StartIndex,
  645. totalCount,
  646. returnItems.ToArray());
  647. }
  648. private bool RequiresPostFiltering2(InternalItemsQuery query)
  649. {
  650. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes[0] == BaseItemKind.BoxSet)
  651. {
  652. Logger.LogDebug("Query requires post-filtering due to BoxSet query");
  653. return true;
  654. }
  655. return false;
  656. }
  657. private bool RequiresPostFiltering(InternalItemsQuery query)
  658. {
  659. if (LinkedChildren.Length > 0)
  660. {
  661. if (this is not ICollectionFolder)
  662. {
  663. Logger.LogDebug("{Type}: Query requires post-filtering due to LinkedChildren.", GetType().Name);
  664. return true;
  665. }
  666. }
  667. // Filter by Video3DFormat
  668. if (query.Is3D.HasValue)
  669. {
  670. Logger.LogDebug("Query requires post-filtering due to Is3D");
  671. return true;
  672. }
  673. if (query.HasOfficialRating.HasValue)
  674. {
  675. Logger.LogDebug("Query requires post-filtering due to HasOfficialRating");
  676. return true;
  677. }
  678. if (query.IsPlaceHolder.HasValue)
  679. {
  680. Logger.LogDebug("Query requires post-filtering due to IsPlaceHolder");
  681. return true;
  682. }
  683. if (query.HasSpecialFeature.HasValue)
  684. {
  685. Logger.LogDebug("Query requires post-filtering due to HasSpecialFeature");
  686. return true;
  687. }
  688. if (query.HasSubtitles.HasValue)
  689. {
  690. Logger.LogDebug("Query requires post-filtering due to HasSubtitles");
  691. return true;
  692. }
  693. if (query.HasTrailer.HasValue)
  694. {
  695. Logger.LogDebug("Query requires post-filtering due to HasTrailer");
  696. return true;
  697. }
  698. if (query.HasThemeSong.HasValue)
  699. {
  700. Logger.LogDebug("Query requires post-filtering due to HasThemeSong");
  701. return true;
  702. }
  703. if (query.HasThemeVideo.HasValue)
  704. {
  705. Logger.LogDebug("Query requires post-filtering due to HasThemeVideo");
  706. return true;
  707. }
  708. // Filter by VideoType
  709. if (query.VideoTypes.Length > 0)
  710. {
  711. Logger.LogDebug("Query requires post-filtering due to VideoTypes");
  712. return true;
  713. }
  714. if (CollapseBoxSetItems(query, this, query.User, ConfigurationManager))
  715. {
  716. Logger.LogDebug("Query requires post-filtering due to CollapseBoxSetItems");
  717. return true;
  718. }
  719. if (!string.IsNullOrEmpty(query.AdjacentTo))
  720. {
  721. Logger.LogDebug("Query requires post-filtering due to AdjacentTo");
  722. return true;
  723. }
  724. if (query.SeriesStatuses.Length > 0)
  725. {
  726. Logger.LogDebug("Query requires post-filtering due to SeriesStatuses");
  727. return true;
  728. }
  729. if (query.AiredDuringSeason.HasValue)
  730. {
  731. Logger.LogDebug("Query requires post-filtering due to AiredDuringSeason");
  732. return true;
  733. }
  734. if (query.IsPlayed.HasValue)
  735. {
  736. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(BaseItemKind.Series))
  737. {
  738. Logger.LogDebug("Query requires post-filtering due to IsPlayed");
  739. return true;
  740. }
  741. }
  742. return false;
  743. }
  744. private static BaseItem[] SortItemsByRequest(InternalItemsQuery query, IReadOnlyList<BaseItem> items)
  745. {
  746. 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.Equals(itemId))
  1234. {
  1235. return true;
  1236. }
  1237. continue;
  1238. }
  1239. var child = GetLinkedChild(i);
  1240. if (child != null && child.Id.Equals(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, IReadOnlyList<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. }