Folder.cs 59 KB

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