2
0

Folder.cs 59 KB

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