Folder.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833
  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)
  1186. {
  1187. if (i.ItemId.Value == itemId)
  1188. {
  1189. return true;
  1190. }
  1191. continue;
  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. }