2
0

Folder.cs 59 KB

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