Folder.cs 56 KB

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