Folder.cs 59 KB

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