2
0

Folder.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834
  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)
  1187. {
  1188. if (i.ItemId.Value == itemId)
  1189. {
  1190. return true;
  1191. }
  1192. continue;
  1193. }
  1194. var child = GetLinkedChild(i);
  1195. if (child != null && child.Id == itemId)
  1196. {
  1197. return true;
  1198. }
  1199. }
  1200. return false;
  1201. }
  1202. public List<BaseItem> GetLinkedChildren(User user)
  1203. {
  1204. if (!FilterLinkedChildrenPerUser || user == null)
  1205. {
  1206. return GetLinkedChildren();
  1207. }
  1208. var linkedChildren = LinkedChildren;
  1209. var list = new List<BaseItem>(linkedChildren.Length);
  1210. if (linkedChildren.Length == 0)
  1211. {
  1212. return list;
  1213. }
  1214. var allUserRootChildren = LibraryManager.GetUserRootFolder()
  1215. .GetChildren(user, true)
  1216. .OfType<Folder>()
  1217. .ToList();
  1218. var collectionFolderIds = allUserRootChildren
  1219. .Select(i => i.Id)
  1220. .ToList();
  1221. foreach (var i in linkedChildren)
  1222. {
  1223. var child = GetLinkedChild(i);
  1224. if (child == null)
  1225. {
  1226. continue;
  1227. }
  1228. var childOwner = child.GetOwner() ?? child;
  1229. if (childOwner != null && !(child is IItemByName))
  1230. {
  1231. var childProtocol = childOwner.PathProtocol;
  1232. if (!childProtocol.HasValue || childProtocol.Value != Model.MediaInfo.MediaProtocol.File)
  1233. {
  1234. if (!childOwner.IsVisibleStandalone(user))
  1235. {
  1236. continue;
  1237. }
  1238. }
  1239. else
  1240. {
  1241. var itemCollectionFolderIds =
  1242. LibraryManager.GetCollectionFolders(childOwner, allUserRootChildren).Select(f => f.Id);
  1243. if (!itemCollectionFolderIds.Any(collectionFolderIds.Contains))
  1244. {
  1245. continue;
  1246. }
  1247. }
  1248. }
  1249. list.Add(child);
  1250. }
  1251. return list;
  1252. }
  1253. /// <summary>
  1254. /// Gets the linked children.
  1255. /// </summary>
  1256. /// <returns>IEnumerable{BaseItem}.</returns>
  1257. public IEnumerable<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  1258. {
  1259. return LinkedChildren
  1260. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  1261. .Where(i => i.Item2 != null);
  1262. }
  1263. [JsonIgnore]
  1264. protected override bool SupportsOwnedItems => base.SupportsOwnedItems || SupportsShortcutChildren;
  1265. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1266. {
  1267. var changesFound = false;
  1268. if (IsFileProtocol)
  1269. {
  1270. if (RefreshLinkedChildren(fileSystemChildren))
  1271. {
  1272. changesFound = true;
  1273. }
  1274. }
  1275. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1276. return baseHasChanges || changesFound;
  1277. }
  1278. /// <summary>
  1279. /// Refreshes the linked children.
  1280. /// </summary>
  1281. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1282. protected virtual bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  1283. {
  1284. if (SupportsShortcutChildren)
  1285. {
  1286. var newShortcutLinks = fileSystemChildren
  1287. .Where(i => !i.IsDirectory && FileSystem.IsShortcut(i.FullName))
  1288. .Select(i =>
  1289. {
  1290. try
  1291. {
  1292. Logger.LogDebug("Found shortcut at {0}", i.FullName);
  1293. var resolvedPath = CollectionFolder.ApplicationHost.ExpandVirtualPath(FileSystem.ResolveShortcut(i.FullName));
  1294. if (!string.IsNullOrEmpty(resolvedPath))
  1295. {
  1296. return new LinkedChild
  1297. {
  1298. Path = resolvedPath,
  1299. Type = LinkedChildType.Shortcut
  1300. };
  1301. }
  1302. Logger.LogError("Error resolving shortcut {0}", i.FullName);
  1303. return null;
  1304. }
  1305. catch (IOException ex)
  1306. {
  1307. Logger.LogError(ex, "Error resolving shortcut {0}", i.FullName);
  1308. return null;
  1309. }
  1310. })
  1311. .Where(i => i != null)
  1312. .ToList();
  1313. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1314. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer(FileSystem)))
  1315. {
  1316. Logger.LogInformation("Shortcut links have changed for {0}", Path);
  1317. newShortcutLinks.AddRange(LinkedChildren.Where(i => i.Type == LinkedChildType.Manual));
  1318. LinkedChildren = newShortcutLinks.ToArray();
  1319. return true;
  1320. }
  1321. }
  1322. foreach (var child in LinkedChildren)
  1323. {
  1324. // Reset the cached value
  1325. child.ItemId = null;
  1326. }
  1327. return false;
  1328. }
  1329. /// <summary>
  1330. /// Marks the played.
  1331. /// </summary>
  1332. /// <param name="user">The user.</param>
  1333. /// <param name="datePlayed">The date played.</param>
  1334. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1335. /// <returns>Task.</returns>
  1336. public override void MarkPlayed(
  1337. User user,
  1338. DateTime? datePlayed,
  1339. bool resetPosition)
  1340. {
  1341. var query = new InternalItemsQuery
  1342. {
  1343. User = user,
  1344. Recursive = true,
  1345. IsFolder = false,
  1346. EnableTotalRecordCount = false
  1347. };
  1348. if (!user.DisplayMissingEpisodes)
  1349. {
  1350. query.IsVirtualItem = false;
  1351. }
  1352. var itemsResult = GetItemList(query);
  1353. // Sweep through recursively and update status
  1354. foreach (var item in itemsResult)
  1355. {
  1356. if (item.IsVirtualItem)
  1357. {
  1358. // The querying doesn't support virtual unaired
  1359. var episode = item as Episode;
  1360. if (episode != null && episode.IsUnaired)
  1361. {
  1362. continue;
  1363. }
  1364. }
  1365. item.MarkPlayed(user, datePlayed, resetPosition);
  1366. }
  1367. }
  1368. /// <summary>
  1369. /// Marks the unplayed.
  1370. /// </summary>
  1371. /// <param name="user">The user.</param>
  1372. /// <returns>Task.</returns>
  1373. public override void MarkUnplayed(User user)
  1374. {
  1375. var itemsResult = GetItemList(new InternalItemsQuery
  1376. {
  1377. User = user,
  1378. Recursive = true,
  1379. IsFolder = false,
  1380. EnableTotalRecordCount = false
  1381. });
  1382. // Sweep through recursively and update status
  1383. foreach (var item in itemsResult)
  1384. {
  1385. item.MarkUnplayed(user);
  1386. }
  1387. }
  1388. public override bool IsPlayed(User user)
  1389. {
  1390. var itemsResult = GetItemList(new InternalItemsQuery(user)
  1391. {
  1392. Recursive = true,
  1393. IsFolder = false,
  1394. IsVirtualItem = false,
  1395. EnableTotalRecordCount = false
  1396. });
  1397. return itemsResult
  1398. .All(i => i.IsPlayed(user));
  1399. }
  1400. public override bool IsUnplayed(User user)
  1401. {
  1402. return !IsPlayed(user);
  1403. }
  1404. [JsonIgnore]
  1405. public virtual bool SupportsUserDataFromChildren
  1406. {
  1407. get
  1408. {
  1409. // These are just far too slow.
  1410. if (this is ICollectionFolder)
  1411. {
  1412. return false;
  1413. }
  1414. if (this is UserView)
  1415. {
  1416. return false;
  1417. }
  1418. if (this is UserRootFolder)
  1419. {
  1420. return false;
  1421. }
  1422. if (this is Channel)
  1423. {
  1424. return false;
  1425. }
  1426. if (SourceType != SourceType.Library)
  1427. {
  1428. return false;
  1429. }
  1430. var iItemByName = this as IItemByName;
  1431. if (iItemByName != null)
  1432. {
  1433. var hasDualAccess = this as IHasDualAccess;
  1434. if (hasDualAccess == null || hasDualAccess.IsAccessedByName)
  1435. {
  1436. return false;
  1437. }
  1438. }
  1439. return true;
  1440. }
  1441. }
  1442. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields)
  1443. {
  1444. if (!SupportsUserDataFromChildren)
  1445. {
  1446. return;
  1447. }
  1448. if (itemDto != null)
  1449. {
  1450. if (fields.ContainsField(ItemFields.RecursiveItemCount))
  1451. {
  1452. itemDto.RecursiveItemCount = GetRecursiveChildCount(user);
  1453. }
  1454. }
  1455. if (SupportsPlayedStatus)
  1456. {
  1457. var unplayedQueryResult = GetItems(new InternalItemsQuery(user)
  1458. {
  1459. Recursive = true,
  1460. IsFolder = false,
  1461. IsVirtualItem = false,
  1462. EnableTotalRecordCount = true,
  1463. Limit = 0,
  1464. IsPlayed = false,
  1465. DtoOptions = new DtoOptions(false)
  1466. {
  1467. EnableImages = false
  1468. }
  1469. });
  1470. double unplayedCount = unplayedQueryResult.TotalRecordCount;
  1471. dto.UnplayedItemCount = unplayedQueryResult.TotalRecordCount;
  1472. if (itemDto != null && itemDto.RecursiveItemCount.HasValue)
  1473. {
  1474. if (itemDto.RecursiveItemCount.Value > 0)
  1475. {
  1476. var unplayedPercentage = (unplayedCount / itemDto.RecursiveItemCount.Value) * 100;
  1477. dto.PlayedPercentage = 100 - unplayedPercentage;
  1478. dto.Played = dto.PlayedPercentage.Value >= 100;
  1479. }
  1480. }
  1481. else
  1482. {
  1483. dto.Played = (dto.UnplayedItemCount ?? 0) == 0;
  1484. }
  1485. }
  1486. }
  1487. /// <summary>
  1488. /// Contains constants used when reporting scan progress.
  1489. /// </summary>
  1490. private static class ProgressHelpers
  1491. {
  1492. /// <summary>
  1493. /// Reported after the folders immediate children are retrieved.
  1494. /// </summary>
  1495. public const int RetrievedChildren = 5;
  1496. /// <summary>
  1497. /// Reported after add, updating, or deleting child items from the LibraryManager.
  1498. /// </summary>
  1499. public const int UpdatedChildItems = 10;
  1500. /// <summary>
  1501. /// Reported once subfolders are scanned.
  1502. /// When scanning subfolders, the progress will be between [UpdatedItems, ScannedSubfolders].
  1503. /// </summary>
  1504. public const int ScannedSubfolders = 50;
  1505. /// <summary>
  1506. /// Reported once metadata is refreshed.
  1507. /// When refreshing metadata, the progress will be between [ScannedSubfolders, MetadataRefreshed].
  1508. /// </summary>
  1509. public const int RefreshedMetadata = 100;
  1510. /// <summary>
  1511. /// Gets the current progress given the previous step, next step, and progress in between.
  1512. /// </summary>
  1513. /// <param name="previousProgressStep">The previous progress step.</param>
  1514. /// <param name="nextProgressStep">The next progress step.</param>
  1515. /// <param name="currentProgress">The current progress step.</param>
  1516. /// <returns>The progress.</returns>
  1517. public static double GetProgress(int previousProgressStep, int nextProgressStep, double currentProgress)
  1518. {
  1519. return previousProgressStep + ((nextProgressStep - previousProgressStep) * (currentProgress / 100));
  1520. }
  1521. }
  1522. }
  1523. }