Folder.cs 59 KB

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