Folder.cs 60 KB

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