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