Folder.cs 60 KB

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